numpy API Reference
Full documentation for numpy (2.1.3)
numpy.False_
Python Library Documentation: bool object class bool(generic) | Boolean type (True or False), stored as a byte. | | .. warning:: | | The :class:`bool` type is not a subclass of the :class:`int_` type | (the :class:`bool` is not even a number type). This is different | than Python's default implementation of :class:`bool` as a | sub-class of :class:`int`. | | :Character code: ``'?'`` | | Method resolution order: | bool | generic | builtins.object | | Methods defined here: | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __repr__(self, /) | Return repr(self). | | __ror__(self, value, /) | Return value|self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __xor__(self, value, /) | Return self^value. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.ScalarType
Python Library Documentation: tuple object class tuple(object) | tuple(iterable=(), /) | | Built-in immutable sequence. | | If no argument is given, the constructor returns an empty tuple. | If iterable is specified the tuple is initialized from iterable's items. | | If the argument is a tuple, the return value is the same object. | | Built-in subclasses: | asyncgen_hooks | UnraisableHookArgs | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return bool(key in self). | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __rmul__(self, value, /) | Return value*self. | | count(self, value, /) | Return number of occurrences of value. | | index(self, value, start=0, stop=9223372036854775807, /) | Return first index of value. | | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | See PEP 585 | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature.
numpy.True_
Python Library Documentation: bool object class bool(generic) | Boolean type (True or False), stored as a byte. | | .. warning:: | | The :class:`bool` type is not a subclass of the :class:`int_` type | (the :class:`bool` is not even a number type). This is different | than Python's default implementation of :class:`bool` as a | sub-class of :class:`int`. | | :Character code: ``'?'`` | | Method resolution order: | bool | generic | builtins.object | | Methods defined here: | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __repr__(self, /) | Return repr(self). | | __ror__(self, value, /) | Return value|self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __xor__(self, value, /) | Return self^value. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.abs
Python Library Documentation: ufunc
absolute = <ufunc 'absolute'>
absolute(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Calculate the absolute value element-wise.
``np.abs`` is a shorthand for this function.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
absolute : ndarray
An ndarray containing the absolute value of
each element in `x`. For complex input, ``a + ib``, the
absolute value is :math:`\sqrt{ a^2 + b^2 }`.
This is a scalar if `x` is a scalar.
Examples
--------
>>> import numpy as np
>>> x = np.array([-1.2, 1.2])
>>> np.absolute(x)
array([ 1.2, 1.2])
>>> np.absolute(1.2 + 1j)
1.5620499351813308
Plot the function over ``[-10, 10]``:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(start=-10, stop=10, num=101)
>>> plt.plot(x, np.absolute(x))
>>> plt.show()
Plot the function over the complex plane:
>>> xx = x + 1j * x[:, np.newaxis]
>>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray')
>>> plt.show()
The `abs` function can be used as a shorthand for ``np.absolute`` on
ndarrays.
>>> x = np.array([-1.2, 1.2])
>>> abs(x)
array([1.2, 1.2])
numpy.absolute
Python Library Documentation: ufunc
absolute = <ufunc 'absolute'>
absolute(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Calculate the absolute value element-wise.
``np.abs`` is a shorthand for this function.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
absolute : ndarray
An ndarray containing the absolute value of
each element in `x`. For complex input, ``a + ib``, the
absolute value is :math:`\sqrt{ a^2 + b^2 }`.
This is a scalar if `x` is a scalar.
Examples
--------
>>> import numpy as np
>>> x = np.array([-1.2, 1.2])
>>> np.absolute(x)
array([ 1.2, 1.2])
>>> np.absolute(1.2 + 1j)
1.5620499351813308
Plot the function over ``[-10, 10]``:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(start=-10, stop=10, num=101)
>>> plt.plot(x, np.absolute(x))
>>> plt.show()
Plot the function over the complex plane:
>>> xx = x + 1j * x[:, np.newaxis]
>>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray')
>>> plt.show()
The `abs` function can be used as a shorthand for ``np.absolute`` on
ndarrays.
>>> x = np.array([-1.2, 1.2])
>>> abs(x)
array([1.2, 1.2])
numpy.acos
Python Library Documentation: ufunc
arccos = <ufunc 'arccos'>
arccos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Trigonometric inverse cosine, element-wise.
The inverse of `cos` so that, if ``y = cos(x)``, then ``x = arccos(y)``.
Parameters
----------
x : array_like
`x`-coordinate on the unit circle.
For real arguments, the domain is [-1, 1].
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
angle : ndarray
The angle of the ray intersecting the unit circle at the given
`x`-coordinate in radians [0, pi].
This is a scalar if `x` is a scalar.
See Also
--------
cos, arctan, arcsin, emath.arccos
Notes
-----
`arccos` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that ``cos(z) = x``. The convention is to return
the angle `z` whose real part lies in `[0, pi]`.
For real-valued input data types, `arccos` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arccos` is a complex analytic function that
has branch cuts ``[-inf, -1]`` and `[1, inf]` and is continuous from
above on the former and from below on the latter.
The inverse `cos` is also known as `acos` or cos^-1.
References
----------
M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 79.
https://personal.math.ubc.ca/~cbm/aands/page_79.htm
Examples
--------
>>> import numpy as np
We expect the arccos of 1 to be 0, and of -1 to be pi:
>>> np.arccos([1, -1])
array([ 0. , 3.14159265])
Plot arccos:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-1, 1, num=100)
>>> plt.plot(x, np.arccos(x))
>>> plt.axis('tight')
>>> plt.show()
numpy.acosh
Python Library Documentation: ufunc
arccosh = <ufunc 'arccosh'>
arccosh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse hyperbolic cosine, element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
arccosh : ndarray
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
See Also
--------
cosh, arcsinh, sinh, arctanh, tanh
Notes
-----
`arccosh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `cosh(z) = x`. The convention is to return the
`z` whose imaginary part lies in ``[-pi, pi]`` and the real part in
``[0, inf]``.
For real-valued input data types, `arccosh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arccosh` is a complex analytical function that
has a branch cut `[-inf, 1]` and is continuous from above on it.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86.
https://personal.math.ubc.ca/~cbm/aands/page_86.htm
.. [2] Wikipedia, "Inverse hyperbolic function",
https://en.wikipedia.org/wiki/Arccosh
Examples
--------
>>> import numpy as np
>>> np.arccosh([np.e, 10.0])
array([ 1.65745445, 2.99322285])
>>> np.arccosh(1)
0.0
numpy.add
Python Library Documentation: ufunc
add = <ufunc 'add'>
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
add : ndarray or scalar
The sum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.
Examples
--------
>>> import numpy as np
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
The ``+`` operator can be used as a shorthand for ``np.add`` on ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 + x2
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
numpy.all
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
all(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)
Test whether all array elements along a given axis evaluate to True.
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : None or int or tuple of ints, optional
Axis or axes along which a logical AND reduction is performed.
The default (``axis=None``) is to perform a logical AND over all
the dimensions of the input array. `axis` may be negative, in
which case it counts from the last to the first axis.
.. versionadded:: 1.7.0
If this is a tuple of ints, a reduction is performed on multiple
axes, instead of a single axis or all the axes as before.
out : ndarray, optional
Alternate output array in which to place the result.
It must have the same shape as the expected output and its
type is preserved (e.g., if ``dtype(out)`` is float, the result
will consist of 0.0's and 1.0's). See :ref:`ufuncs-output-type`
for more details.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `all` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
where : array_like of bool, optional
Elements to include in checking for all `True` values.
See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.20.0
Returns
-------
all : ndarray, bool
A new boolean or array is returned unless `out` is specified,
in which case a reference to `out` is returned.
See Also
--------
ndarray.all : equivalent method
any : Test whether any element along a given axis evaluates to True.
Notes
-----
Not a Number (NaN), positive infinity and negative infinity
evaluate to `True` because these are not equal to zero.
.. versionchanged:: 2.0
Before NumPy 2.0, ``all`` did not return booleans for object dtype
input arrays.
This behavior is still available via ``np.logical_and.reduce``.
Examples
--------
>>> import numpy as np
>>> np.all([[True,False],[True,True]])
False
>>> np.all([[True,False],[True,True]], axis=0)
array([ True, False])
>>> np.all([-1, 4, 5])
True
>>> np.all([1.0, np.nan])
True
>>> np.all([[True, True], [False, True]], where=[[True], [False]])
True
>>> o=np.array(False)
>>> z=np.all([-1, 4, 5], out=o)
>>> id(z), id(o), z
(28293632, 28293632, array(True)) # may vary
numpy.allclose
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
Returns True if two arrays are element-wise equal within a tolerance.
The tolerance values are positive, typically very small numbers. The
relative difference (`rtol` * abs(`b`)) and the absolute difference
`atol` are added together to compare against the absolute difference
between `a` and `b`.
.. warning:: The default `atol` is not appropriate for comparing numbers
with magnitudes much smaller than one (see Notes).
NaNs are treated as equal if they are in the same place and if
``equal_nan=True``. Infs are treated as equal if they are in the same
place and of the same sign in both arrays.
Parameters
----------
a, b : array_like
Input arrays to compare.
rtol : array_like
The relative tolerance parameter (see Notes).
atol : array_like
The absolute tolerance parameter (see Notes).
equal_nan : bool
Whether to compare NaN's as equal. If True, NaN's in `a` will be
considered equal to NaN's in `b` in the output array.
.. versionadded:: 1.10.0
Returns
-------
allclose : bool
Returns True if the two arrays are equal within the given
tolerance; False otherwise.
See Also
--------
isclose, all, any, equal
Notes
-----
If the following equation is element-wise True, then allclose returns
True.::
absolute(a - b) <= (atol + rtol * absolute(b))
The above equation is not symmetric in `a` and `b`, so that
``allclose(a, b)`` might be different from ``allclose(b, a)`` in
some rare cases.
The default value of `atol` is not appropriate when the reference value
`b` has magnitude smaller than one. For example, it is unlikely that
``a = 1e-9`` and ``b = 2e-9`` should be considered "close", yet
``allclose(1e-9, 2e-9)`` is ``True`` with default settings. Be sure
to select `atol` for the use case at hand, especially for defining the
threshold below which a non-zero value in `a` will be considered "close"
to a very small or zero value in `b`.
The comparison of `a` and `b` uses standard broadcasting, which
means that `a` and `b` need not have the same shape in order for
``allclose(a, b)`` to evaluate to True. The same is true for
`equal` but not `array_equal`.
`allclose` is not defined for non-numeric data types.
`bool` is considered a numeric data-type for this purpose.
Examples
--------
>>> import numpy as np
>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
False
>>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
True
>>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
True
numpy.amax
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
amax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the maximum of an array or maximum along an axis.
`amax` is an alias of `~numpy.max`.
See Also
--------
max : alias of this function
ndarray.max : equivalent method
numpy.amin
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the minimum of an array or minimum along an axis.
`amin` is an alias of `~numpy.min`.
See Also
--------
min : alias of this function
ndarray.min : equivalent method
numpy.angle
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
angle(z, deg=False)
Return the angle of the complex argument.
Parameters
----------
z : array_like
A complex number or sequence of complex numbers.
deg : bool, optional
Return angle in degrees if True, radians if False (default).
Returns
-------
angle : ndarray or scalar
The counterclockwise angle from the positive real axis on the complex
plane in the range ``(-pi, pi]``, with dtype as numpy.float64.
.. versionchanged:: 1.16.0
This function works on subclasses of ndarray like `ma.array`.
See Also
--------
arctan2
absolute
Notes
-----
This function passes the imaginary and real parts of the argument to
`arctan2` to compute the result; consequently, it follows the convention
of `arctan2` when the magnitude of the argument is zero. See example.
Examples
--------
>>> import numpy as np
>>> np.angle([1.0, 1.0j, 1+1j]) # in radians
array([ 0. , 1.57079633, 0.78539816]) # may vary
>>> np.angle(1+1j, deg=True) # in degrees
45.0
>>> np.angle([0., -0., complex(0., -0.), complex(-0., -0.)]) # convention
array([ 0. , 3.14159265, -0. , -3.14159265])
numpy.any
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
any(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)
Test whether any array element along a given axis evaluates to True.
Returns single boolean if `axis` is ``None``
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : None or int or tuple of ints, optional
Axis or axes along which a logical OR reduction is performed.
The default (``axis=None``) is to perform a logical OR over all
the dimensions of the input array. `axis` may be negative, in
which case it counts from the last to the first axis.
.. versionadded:: 1.7.0
If this is a tuple of ints, a reduction is performed on multiple
axes, instead of a single axis or all the axes as before.
out : ndarray, optional
Alternate output array in which to place the result. It must have
the same shape as the expected output and its type is preserved
(e.g., if it is of type float, then it will remain so, returning
1.0 for True and 0.0 for False, regardless of the type of `a`).
See :ref:`ufuncs-output-type` for more details.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `any` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
where : array_like of bool, optional
Elements to include in checking for any `True` values.
See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.20.0
Returns
-------
any : bool or ndarray
A new boolean or `ndarray` is returned unless `out` is specified,
in which case a reference to `out` is returned.
See Also
--------
ndarray.any : equivalent method
all : Test whether all elements along a given axis evaluate to True.
Notes
-----
Not a Number (NaN), positive infinity and negative infinity evaluate
to `True` because these are not equal to zero.
.. versionchanged:: 2.0
Before NumPy 2.0, ``any`` did not return booleans for object dtype
input arrays.
This behavior is still available via ``np.logical_or.reduce``.
Examples
--------
>>> import numpy as np
>>> np.any([[True, False], [True, True]])
True
>>> np.any([[True, False, True ],
... [False, False, False]], axis=0)
array([ True, False, True])
>>> np.any([-1, 0, 5])
True
>>> np.any([[np.nan], [np.inf]], axis=1, keepdims=True)
array([[ True],
[ True]])
>>> np.any([[True, False], [False, False]], where=[[False], [True]])
False
>>> a = np.array([[1, 0, 0],
... [0, 0, 1],
... [0, 0, 0]])
>>> np.any(a, axis=0)
array([ True, False, True])
>>> np.any(a, axis=1)
array([ True, True, False])
>>> o=np.array(False)
>>> z=np.any([-1, 4, 5], out=o)
>>> z, o
(array(True), array(True))
>>> # Check now that z is a reference to o
>>> z is o
True
>>> id(z), id(o) # identity of z and o # doctest: +SKIP
(191614240, 191614240)
numpy.append
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
append(arr, values, axis=None)
Append values to the end of an array.
Parameters
----------
arr : array_like
Values are appended to a copy of this array.
values : array_like
These values are appended to a copy of `arr`. It must be of the
correct shape (the same shape as `arr`, excluding `axis`). If
`axis` is not specified, `values` can be any shape and will be
flattened before use.
axis : int, optional
The axis along which `values` are appended. If `axis` is not
given, both `arr` and `values` are flattened before use.
Returns
-------
append : ndarray
A copy of `arr` with `values` appended to `axis`. Note that
`append` does not occur in-place: a new array is allocated and
filled. If `axis` is None, `out` is a flattened array.
See Also
--------
insert : Insert elements into an array.
delete : Delete elements from an array.
Examples
--------
>>> import numpy as np
>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
array([1, 2, 3, ..., 7, 8, 9])
When `axis` is specified, `values` must have the correct shape.
>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
Traceback (most recent call last):
...
ValueError: all the input arrays must have same number of dimensions, but
the array at index 0 has 2 dimension(s) and the array at index 1 has 1
dimension(s)
>>> a = np.array([1, 2], dtype=int)
>>> c = np.append(a, [])
>>> c
array([1., 2.])
>>> c.dtype
float64
Default dtype for empty ndarrays is `float64` thus making the output of dtype
`float64` when appended with dtype `int64`
numpy.apply_along_axis
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
apply_along_axis(func1d, axis, arr, *args, **kwargs)
Apply a function to 1-D slices along the given axis.
Execute `func1d(a, *args, **kwargs)` where `func1d` operates on 1-D arrays
and `a` is a 1-D slice of `arr` along `axis`.
This is equivalent to (but faster than) the following use of `ndindex` and
`s_`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of indices::
Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
for kk in ndindex(Nk):
f = func1d(arr[ii + s_[:,] + kk])
Nj = f.shape
for jj in ndindex(Nj):
out[ii + jj + kk] = f[jj]
Equivalently, eliminating the inner loop, this can be expressed as::
Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
for kk in ndindex(Nk):
out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])
Parameters
----------
func1d : function (M,) -> (Nj...)
This function should accept 1-D arrays. It is applied to 1-D
slices of `arr` along the specified axis.
axis : integer
Axis along which `arr` is sliced.
arr : ndarray (Ni..., M, Nk...)
Input array.
args : any
Additional arguments to `func1d`.
kwargs : any
Additional named arguments to `func1d`.
.. versionadded:: 1.9.0
Returns
-------
out : ndarray (Ni..., Nj..., Nk...)
The output array. The shape of `out` is identical to the shape of
`arr`, except along the `axis` dimension. This axis is removed, and
replaced with new dimensions equal to the shape of the return value
of `func1d`. So if `func1d` returns a scalar `out` will have one
fewer dimensions than `arr`.
See Also
--------
apply_over_axes : Apply a function repeatedly over multiple axes.
Examples
--------
>>> import numpy as np
>>> def my_func(a):
... """Average first and last element of a 1-D array"""
... return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([4., 5., 6.])
>>> np.apply_along_axis(my_func, 1, b)
array([2., 5., 8.])
For a function that returns a 1D array, the number of dimensions in
`outarr` is the same as `arr`.
>>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
>>> np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
[3, 4, 9],
[2, 5, 6]])
For a function that returns a higher dimensional array, those dimensions
are inserted in place of the `axis` dimension.
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(np.diag, -1, b)
array([[[1, 0, 0],
[0, 2, 0],
[0, 0, 3]],
[[4, 0, 0],
[0, 5, 0],
[0, 0, 6]],
[[7, 0, 0],
[0, 8, 0],
[0, 0, 9]]])
numpy.apply_over_axes
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
apply_over_axes(func, a, axes)
Apply a function repeatedly over multiple axes.
`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`. The result `res` of the function call must have
either the same dimensions as `a` or one less dimension. If `res`
has one less dimension than `a`, a dimension is inserted before
`axis`. The call to `func` is then repeated for each axis in `axes`,
with `res` as the first argument.
Parameters
----------
func : function
This function must take two arguments, `func(a, axis)`.
a : array_like
Input array.
axes : array_like
Axes over which `func` is applied; the elements must be integers.
Returns
-------
apply_over_axis : ndarray
The output array. The number of dimensions is the same as `a`,
but the shape can be different. This depends on whether `func`
changes the shape of its output with respect to its input.
See Also
--------
apply_along_axis :
Apply a function to 1-D slices of an array along the given axis.
Notes
-----
This function is equivalent to tuple axis arguments to reorderable ufuncs
with keepdims=True. Tuple axis arguments to ufuncs have been available since
version 1.7.0.
Examples
--------
>>> import numpy as np
>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
Sum over axes 0 and 2. The result has same number of dimensions
as the original array:
>>> np.apply_over_axes(np.sum, a, [0,2])
array([[[ 60],
[ 92],
[124]]])
Tuple axis arguments to ufuncs are equivalent:
>>> np.sum(a, axis=(0,2), keepdims=True)
array([[[ 60],
[ 92],
[124]]])
numpy.arange
Python Library Documentation: built-in function arange in module numpy
arange(...)
arange([start,] stop[, step,], dtype=None, *, device=None, like=None)
Return evenly spaced values within a given interval.
``arange`` can be called with a varying number of positional arguments:
* ``arange(stop)``: Values are generated within the half-open interval
``[0, stop)`` (in other words, the interval including `start` but
excluding `stop`).
* ``arange(start, stop)``: Values are generated within the half-open
interval ``[start, stop)``.
* ``arange(start, stop, step)`` Values are generated within the half-open
interval ``[start, stop)``, with spacing between values given by
``step``.
For integer arguments the function is roughly equivalent to the Python
built-in :py:class:`range`, but returns an ndarray rather than a ``range``
instance.
When using a non-integer step, such as 0.1, it is often better to use
`numpy.linspace`.
See the Warning sections below for more information.
Parameters
----------
start : integer or real, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : integer or real
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : integer or real, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
dtype : dtype, optional
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
device : str, optional
The device on which to place the created array. Default: ``None``.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
arange : ndarray
Array of evenly spaced values.
For floating point arguments, the length of the result is
``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.
Warnings
--------
The length of the output might not be numerically stable.
Another stability issue is due to the internal implementation of
`numpy.arange`.
The actual step value used to populate the array is
``dtype(start + step) - dtype(start)`` and not `step`. Precision loss
can occur here, due to casting or due to using floating points when
`start` is much larger than `step`. This can lead to unexpected
behaviour. For example::
>>> np.arange(0, 5, 0.5, dtype=int)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> np.arange(-3, 3, 0.5, dtype=int)
array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
In such cases, the use of `numpy.linspace` should be preferred.
The built-in :py:class:`range` generates :std:doc:`Python built-in integers
that have arbitrary size <python:c-api/long>`, while `numpy.arange`
produces `numpy.int32` or `numpy.int64` numbers. This may result in
incorrect results for large integer values::
>>> power = 40
>>> modulo = 10000
>>> x1 = [(n ** power) % modulo for n in range(8)]
>>> x2 = [(n ** power) % modulo for n in np.arange(8)]
>>> print(x1)
[0, 1, 7776, 8801, 6176, 625, 6576, 4001] # correct
>>> print(x2)
[0, 1, 7776, 7185, 0, 5969, 4816, 3361] # incorrect
See Also
--------
numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
:ref:`how-to-partition`
Examples
--------
>>> import numpy as np
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
numpy.arccos
Python Library Documentation: ufunc
arccos = <ufunc 'arccos'>
arccos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Trigonometric inverse cosine, element-wise.
The inverse of `cos` so that, if ``y = cos(x)``, then ``x = arccos(y)``.
Parameters
----------
x : array_like
`x`-coordinate on the unit circle.
For real arguments, the domain is [-1, 1].
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
angle : ndarray
The angle of the ray intersecting the unit circle at the given
`x`-coordinate in radians [0, pi].
This is a scalar if `x` is a scalar.
See Also
--------
cos, arctan, arcsin, emath.arccos
Notes
-----
`arccos` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that ``cos(z) = x``. The convention is to return
the angle `z` whose real part lies in `[0, pi]`.
For real-valued input data types, `arccos` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arccos` is a complex analytic function that
has branch cuts ``[-inf, -1]`` and `[1, inf]` and is continuous from
above on the former and from below on the latter.
The inverse `cos` is also known as `acos` or cos^-1.
References
----------
M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 79.
https://personal.math.ubc.ca/~cbm/aands/page_79.htm
Examples
--------
>>> import numpy as np
We expect the arccos of 1 to be 0, and of -1 to be pi:
>>> np.arccos([1, -1])
array([ 0. , 3.14159265])
Plot arccos:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-1, 1, num=100)
>>> plt.plot(x, np.arccos(x))
>>> plt.axis('tight')
>>> plt.show()
numpy.arccosh
Python Library Documentation: ufunc
arccosh = <ufunc 'arccosh'>
arccosh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse hyperbolic cosine, element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
arccosh : ndarray
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
See Also
--------
cosh, arcsinh, sinh, arctanh, tanh
Notes
-----
`arccosh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `cosh(z) = x`. The convention is to return the
`z` whose imaginary part lies in ``[-pi, pi]`` and the real part in
``[0, inf]``.
For real-valued input data types, `arccosh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arccosh` is a complex analytical function that
has a branch cut `[-inf, 1]` and is continuous from above on it.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86.
https://personal.math.ubc.ca/~cbm/aands/page_86.htm
.. [2] Wikipedia, "Inverse hyperbolic function",
https://en.wikipedia.org/wiki/Arccosh
Examples
--------
>>> import numpy as np
>>> np.arccosh([np.e, 10.0])
array([ 1.65745445, 2.99322285])
>>> np.arccosh(1)
0.0
numpy.arcsin
Python Library Documentation: ufunc
arcsin = <ufunc 'arcsin'>
arcsin(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse sine, element-wise.
Parameters
----------
x : array_like
`y`-coordinate on the unit circle.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
angle : ndarray
The inverse sine of each element in `x`, in radians and in the
closed interval ``[-pi/2, pi/2]``.
This is a scalar if `x` is a scalar.
See Also
--------
sin, cos, arccos, tan, arctan, arctan2, emath.arcsin
Notes
-----
`arcsin` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that :math:`sin(z) = x`. The convention is to
return the angle `z` whose real part lies in [-pi/2, pi/2].
For real-valued input data types, *arcsin* always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arcsin` is a complex analytic function that
has, by convention, the branch cuts [-inf, -1] and [1, inf] and is
continuous from above on the former and from below on the latter.
The inverse sine is also known as `asin` or sin^{-1}.
References
----------
Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*,
10th printing, New York: Dover, 1964, pp. 79ff.
https://personal.math.ubc.ca/~cbm/aands/page_79.htm
Examples
--------
>>> import numpy as np
>>> np.arcsin(1) # pi/2
1.5707963267948966
>>> np.arcsin(-1) # -pi/2
-1.5707963267948966
>>> np.arcsin(0)
0.0
numpy.arcsinh
Python Library Documentation: ufunc
arcsinh = <ufunc 'arcsinh'>
arcsinh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse hyperbolic sine element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
Notes
-----
`arcsinh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `sinh(z) = x`. The convention is to return the
`z` whose imaginary part lies in `[-pi/2, pi/2]`.
For real-valued input data types, `arcsinh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
returns ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arcsinh` is a complex analytical function that
has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from
the right on the former and from the left on the latter.
The inverse hyperbolic sine is also known as `asinh` or ``sinh^-1``.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86.
https://personal.math.ubc.ca/~cbm/aands/page_86.htm
.. [2] Wikipedia, "Inverse hyperbolic function",
https://en.wikipedia.org/wiki/Arcsinh
Examples
--------
>>> import numpy as np
>>> np.arcsinh(np.array([np.e, 10.0]))
array([ 1.72538256, 2.99822295])
numpy.arctan
Python Library Documentation: ufunc
arctan = <ufunc 'arctan'>
arctan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Trigonometric inverse tangent, element-wise.
The inverse of tan, so that if ``y = tan(x)`` then ``x = arctan(y)``.
Parameters
----------
x : array_like
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Out has the same shape as `x`. Its real part is in
``[-pi/2, pi/2]`` (``arctan(+/-inf)`` returns ``+/-pi/2``).
This is a scalar if `x` is a scalar.
See Also
--------
arctan2 : The "four quadrant" arctan of the angle formed by (`x`, `y`)
and the positive `x`-axis.
angle : Argument of complex values.
Notes
-----
`arctan` is a multi-valued function: for each `x` there are infinitely
many numbers `z` such that tan(`z`) = `x`. The convention is to return
the angle `z` whose real part lies in [-pi/2, pi/2].
For real-valued input data types, `arctan` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arctan` is a complex analytic function that
has [``1j, infj``] and [``-1j, -infj``] as branch cuts, and is continuous
from the left on the former and from the right on the latter.
The inverse tangent is also known as `atan` or tan^{-1}.
References
----------
Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*,
10th printing, New York: Dover, 1964, pp. 79.
https://personal.math.ubc.ca/~cbm/aands/page_79.htm
Examples
--------
We expect the arctan of 0 to be 0, and of 1 to be pi/4:
>>> import numpy as np
>>> np.arctan([0, 1])
array([ 0. , 0.78539816])
>>> np.pi/4
0.78539816339744828
Plot arctan:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-10, 10)
>>> plt.plot(x, np.arctan(x))
>>> plt.axis('tight')
>>> plt.show()
numpy.arctan2
Python Library Documentation: ufunc
arctan2 = <ufunc 'arctan2'>
arctan2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly.
The quadrant (i.e., branch) is chosen so that ``arctan2(x1, x2)`` is
the signed angle in radians between the ray ending at the origin and
passing through the point (1,0), and the ray ending at the origin and
passing through the point (`x2`, `x1`). (Note the role reversal: the
"`y`-coordinate" is the first function parameter, the "`x`-coordinate"
is the second.) By IEEE convention, this function is defined for
`x2` = +/-0 and for either or both of `x1` and `x2` = +/-inf (see
Notes for specific values).
This function is not defined for complex-valued arguments; for the
so-called argument of complex values, use `angle`.
Parameters
----------
x1 : array_like, real-valued
`y`-coordinates.
x2 : array_like, real-valued
`x`-coordinates.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
angle : ndarray
Array of angles in radians, in the range ``[-pi, pi]``.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
arctan, tan, angle
Notes
-----
*arctan2* is identical to the `atan2` function of the underlying
C library. The following special values are defined in the C
standard: [1]_
====== ====== ================
`x1` `x2` `arctan2(x1,x2)`
====== ====== ================
+/- 0 +0 +/- 0
+/- 0 -0 +/- pi
> 0 +/-inf +0 / +pi
< 0 +/-inf -0 / -pi
+/-inf +inf +/- (pi/4)
+/-inf -inf +/- (3*pi/4)
====== ====== ================
Note that +0 and -0 are distinct floating point numbers, as are +inf
and -inf.
References
----------
.. [1] ISO/IEC standard 9899:1999, "Programming language C."
Examples
--------
Consider four points in different quadrants:
>>> import numpy as np
>>> x = np.array([-1, +1, +1, -1])
>>> y = np.array([-1, -1, +1, +1])
>>> np.arctan2(y, x) * 180 / np.pi
array([-135., -45., 45., 135.])
Note the order of the parameters. `arctan2` is defined also when `x2` = 0
and at several other special points, obtaining values in
the range ``[-pi, pi]``:
>>> np.arctan2([1., -1.], [0., 0.])
array([ 1.57079633, -1.57079633])
>>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf])
array([0. , 3.14159265, 0.78539816])
numpy.arctanh
Python Library Documentation: ufunc
arctanh = <ufunc 'arctanh'>
arctanh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse hyperbolic tangent element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
See Also
--------
emath.arctanh
Notes
-----
`arctanh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that ``tanh(z) = x``. The convention is to return
the `z` whose imaginary part lies in `[-pi/2, pi/2]`.
For real-valued input data types, `arctanh` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arctanh` is a complex analytical function
that has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from
above on the former and from below on the latter.
The inverse hyperbolic tangent is also known as `atanh` or ``tanh^-1``.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86.
https://personal.math.ubc.ca/~cbm/aands/page_86.htm
.. [2] Wikipedia, "Inverse hyperbolic function",
https://en.wikipedia.org/wiki/Arctanh
Examples
--------
>>> import numpy as np
>>> np.arctanh([0, -0.5])
array([ 0. , -0.54930614])
numpy.argmax
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
argmax(a, axis=None, out=None, *, keepdims=<no value>)
Returns the indices of the maximum values along an axis.
Parameters
----------
a : array_like
Input array.
axis : int, optional
By default, the index is into the flattened array, otherwise
along the specified axis.
out : array, optional
If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.
.. versionadded:: 1.22.0
Returns
-------
index_array : ndarray of ints
Array of indices into the array. It has the same shape as ``a.shape``
with the dimension along `axis` removed. If `keepdims` is set to True,
then the size of `axis` will be 1 with the resulting array having same
shape as ``a.shape``.
See Also
--------
ndarray.argmax, argmin
amax : The maximum value along a given axis.
unravel_index : Convert a flat index into an index tuple.
take_along_axis : Apply ``np.expand_dims(index_array, axis)``
from argmax to an array as if by calling max.
Notes
-----
In case of multiple occurrences of the maximum values, the indices
corresponding to the first occurrence are returned.
Examples
--------
>>> import numpy as np
>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10, 11, 12],
[13, 14, 15]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0)
array([1, 1, 1])
>>> np.argmax(a, axis=1)
array([2, 2])
Indexes of the maximal elements of a N-dimensional array:
>>> ind = np.unravel_index(np.argmax(a, axis=None), a.shape)
>>> ind
(1, 2)
>>> a[ind]
15
>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0, 5, 2, 3, 4, 5])
>>> np.argmax(b) # Only the first occurrence is returned.
1
>>> x = np.array([[4,2,3], [1,0,3]])
>>> index_array = np.argmax(x, axis=-1)
>>> # Same as np.amax(x, axis=-1, keepdims=True)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
array([[4],
[3]])
>>> # Same as np.amax(x, axis=-1)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
... axis=-1).squeeze(axis=-1)
array([4, 3])
Setting `keepdims` to `True`,
>>> x = np.arange(24).reshape((2, 3, 4))
>>> res = np.argmax(x, axis=1, keepdims=True)
>>> res.shape
(2, 1, 4)
numpy.argmin
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
argmin(a, axis=None, out=None, *, keepdims=<no value>)
Returns the indices of the minimum values along an axis.
Parameters
----------
a : array_like
Input array.
axis : int, optional
By default, the index is into the flattened array, otherwise
along the specified axis.
out : array, optional
If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.
.. versionadded:: 1.22.0
Returns
-------
index_array : ndarray of ints
Array of indices into the array. It has the same shape as `a.shape`
with the dimension along `axis` removed. If `keepdims` is set to True,
then the size of `axis` will be 1 with the resulting array having same
shape as `a.shape`.
See Also
--------
ndarray.argmin, argmax
amin : The minimum value along a given axis.
unravel_index : Convert a flat index into an index tuple.
take_along_axis : Apply ``np.expand_dims(index_array, axis)``
from argmin to an array as if by calling min.
Notes
-----
In case of multiple occurrences of the minimum values, the indices
corresponding to the first occurrence are returned.
Examples
--------
>>> import numpy as np
>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10, 11, 12],
[13, 14, 15]])
>>> np.argmin(a)
0
>>> np.argmin(a, axis=0)
array([0, 0, 0])
>>> np.argmin(a, axis=1)
array([0, 0])
Indices of the minimum elements of a N-dimensional array:
>>> ind = np.unravel_index(np.argmin(a, axis=None), a.shape)
>>> ind
(0, 0)
>>> a[ind]
10
>>> b = np.arange(6) + 10
>>> b[4] = 10
>>> b
array([10, 11, 12, 13, 10, 15])
>>> np.argmin(b) # Only the first occurrence is returned.
0
>>> x = np.array([[4,2,3], [1,0,3]])
>>> index_array = np.argmin(x, axis=-1)
>>> # Same as np.amin(x, axis=-1, keepdims=True)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1)
array([[2],
[0]])
>>> # Same as np.amax(x, axis=-1)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1),
... axis=-1).squeeze(axis=-1)
array([2, 0])
Setting `keepdims` to `True`,
>>> x = np.arange(24).reshape((2, 3, 4))
>>> res = np.argmin(x, axis=1, keepdims=True)
>>> res.shape
(2, 1, 4)
numpy.argpartition
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
argpartition(a, kth, axis=-1, kind='introselect', order=None)
Perform an indirect partition along the given axis using the
algorithm specified by the `kind` keyword. It returns an array of
indices of the same shape as `a` that index data along the given
axis in partitioned order.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Array to sort.
kth : int or sequence of ints
Element index to partition by. The k-th element will be in its
final sorted position and all smaller elements will be moved
before it and all larger 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 of them into their sorted
position at once.
.. deprecated:: 1.22.0
Passing booleans as index is deprecated.
axis : int or None, optional
Axis along which to sort. The default is -1 (the last axis). If
None, the flattened array is used.
kind : {'introselect'}, optional
Selection algorithm. Default is 'introselect'
order : str 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, and 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
-------
index_array : ndarray, int
Array of indices that partition `a` along the specified axis.
If `a` is one-dimensional, ``a[index_array]`` yields a partitioned `a`.
More generally, ``np.take_along_axis(a, index_array, axis=axis)``
always yields the partitioned `a`, irrespective of dimensionality.
See Also
--------
partition : Describes partition algorithms used.
ndarray.partition : Inplace partition.
argsort : Full indirect sort.
take_along_axis : Apply ``index_array`` from argpartition
to an array as if by calling partition.
Notes
-----
The returned indices are not guaranteed to be sorted according to
the values. Furthermore, the default selection algorithm ``introselect``
is unstable, and hence the returned indices are not guaranteed
to be the earliest/latest occurrence of the element.
`argpartition` works for real/complex inputs with nan values,
see `partition` for notes on the enhanced sort order and
different selection algorithms.
Examples
--------
One dimensional array:
>>> import numpy as np
>>> x = np.array([3, 4, 2, 1])
>>> x[np.argpartition(x, 3)]
array([2, 1, 3, 4]) # may vary
>>> x[np.argpartition(x, (1, 3))]
array([1, 2, 3, 4]) # may vary
>>> x = [3, 4, 2, 1]
>>> np.array(x)[np.argpartition(x, 3)]
array([2, 1, 3, 4]) # may vary
Multi-dimensional array:
>>> x = np.array([[3, 4, 2], [1, 3, 1]])
>>> index_array = np.argpartition(x, kth=1, axis=-1)
>>> # below is the same as np.partition(x, kth=1)
>>> np.take_along_axis(x, index_array, axis=-1)
array([[2, 3, 4],
[1, 1, 3]])
numpy.argsort
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
argsort(a, axis=-1, kind=None, order=None, *, stable=None)
Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified
by the `kind` keyword. It returns an array of indices of the same shape as
`a` that index data along the given axis in sorted order.
Parameters
----------
a : array_like
Array to sort.
axis : int or None, optional
Axis along which to sort. The default is -1 (the last axis). If None,
the flattened array is used.
kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
and 'mergesort' use timsort under the covers and, in general, the
actual implementation will vary with data type. The 'mergesort' option
is retained for backwards compatibility.
.. versionchanged:: 1.15.0.
The 'stable' option was added.
order : str 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, and 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.
stable : bool, optional
Sort stability. If ``True``, the returned array will maintain
the relative order of ``a`` values which compare as equal.
If ``False`` or ``None``, this is not guaranteed. Internally,
this option selects ``kind='stable'``. Default: ``None``.
.. versionadded:: 2.0.0
Returns
-------
index_array : ndarray, int
Array of indices that sort `a` along the specified `axis`.
If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.
More generally, ``np.take_along_axis(a, index_array, axis=axis)``
always yields the sorted `a`, irrespective of dimensionality.
See Also
--------
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
argpartition : Indirect partial sort.
take_along_axis : Apply ``index_array`` from argsort
to an array as if by calling sort.
Notes
-----
See `sort` for notes on the different sorting algorithms.
As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
nan values. The enhanced sort order is documented in `sort`.
Examples
--------
One dimensional array:
>>> import numpy as np
>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])
Two-dimensional array:
>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
[2, 2]])
>>> ind = np.argsort(x, axis=0) # sorts along first axis (down)
>>> ind
array([[0, 1],
[1, 0]])
>>> np.take_along_axis(x, ind, axis=0) # same as np.sort(x, axis=0)
array([[0, 2],
[2, 3]])
>>> ind = np.argsort(x, axis=1) # sorts along last axis (across)
>>> ind
array([[0, 1],
[0, 1]])
>>> np.take_along_axis(x, ind, axis=1) # same as np.sort(x, axis=1)
array([[0, 3],
[2, 2]])
Indices of the sorted elements of a N-dimensional array:
>>> ind = np.unravel_index(np.argsort(x, axis=None), x.shape)
>>> ind
(array([0, 1, 1, 0]), array([0, 0, 1, 1]))
>>> x[ind] # same as np.sort(x, axis=None)
array([0, 2, 2, 3])
Sorting with keys:
>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
array([(1, 0), (0, 1)],
dtype=[('x', '<i4'), ('y', '<i4')])
>>> np.argsort(x, order=('x','y'))
array([1, 0])
>>> np.argsort(x, order=('y','x'))
array([0, 1])
numpy.argwhere
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
argwhere(a)
Find the indices of array elements that are non-zero, grouped by element.
Parameters
----------
a : array_like
Input data.
Returns
-------
index_array : (N, a.ndim) ndarray
Indices of elements that are non-zero. Indices are grouped by element.
This array will have shape ``(N, a.ndim)`` where ``N`` is the number of
non-zero items.
See Also
--------
where, nonzero
Notes
-----
``np.argwhere(a)`` is almost the same as ``np.transpose(np.nonzero(a))``,
but produces a result of the correct shape for a 0D array.
The output of ``argwhere`` is not suitable for indexing arrays.
For this purpose use ``nonzero(a)`` instead.
Examples
--------
>>> import numpy as np
>>> x = np.arange(6).reshape(2,3)
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.argwhere(x>1)
array([[0, 2],
[1, 0],
[1, 1],
[1, 2]])
numpy.around
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
around(a, decimals=0, out=None)
Round an array to the given number of decimals.
`around` is an alias of `~numpy.round`.
See Also
--------
ndarray.round : equivalent method
round : alias for this function
ceil, fix, floor, rint, trunc
numpy.array
Python Library Documentation: built-in function array in module numpy
array(...)
array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0,
like=None)
Create an array.
Parameters
----------
object : array_like
An array, any object exposing the array interface, an object whose
``__array__`` method returns an array, or any (nested) sequence.
If object is a scalar, a 0-dimensional array containing object is
returned.
dtype : data-type, optional
The desired data-type for the array. If not given, NumPy will try to use
a default ``dtype`` that can represent the values (by applying promotion
rules when necessary.)
copy : bool, optional
If ``True`` (default), then the array data is copied. If ``None``,
a copy will only be made if ``__array__`` returns a copy, if obj is
a nested sequence, or if a copy is needed to satisfy any of the other
requirements (``dtype``, ``order``, etc.). Note that any copy of
the data is shallow, i.e., for arrays with object dtype, the new
array will point to the same objects. See Examples for `ndarray.copy`.
For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
Default: ``True``.
order : {'K', 'A', 'C', 'F'}, optional
Specify the memory layout of the array. If object is not an array, the
newly created array will be in C order (row major) unless 'F' is
specified, in which case it will be in Fortran order (column major).
If object is an array the following holds.
===== ========= ===================================================
order no copy copy=True
===== ========= ===================================================
'K' unchanged F & C order preserved, otherwise most similar order
'A' unchanged F order if input is F and not C, otherwise C order
'C' C order C order
'F' F order F order
===== ========= ===================================================
When ``copy=None`` and a copy is made for other reasons, the result is
the same as if ``copy=True``, with some exceptions for 'A', see the
Notes section. The default order is 'K'.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting
array should have. Ones will be prepended to the shape as
needed to meet this requirement.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
An array object satisfying the specified requirements.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
zeros_like : Return an array of zeros with shape and type of input.
full_like : Return a new array with shape of input filled with value.
empty : Return a new uninitialized array.
ones : Return a new array setting values to one.
zeros : Return a new array setting values to zero.
full : Return a new array of given shape filled with value.
copy: Return an array copy of the given object.
Notes
-----
When order is 'A' and ``object`` is an array in neither 'C' nor 'F' order,
and a copy is forced by a change in dtype, then the order of the result is
not necessarily 'C' as expected. This is likely a bug.
Examples
--------
>>> import numpy as np
>>> np.array([1, 2, 3])
array([1, 2, 3])
Upcasting:
>>> np.array([1, 2, 3.0])
array([ 1., 2., 3.])
More than one dimension:
>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])
Minimum dimensions 2:
>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])
Type provided:
>>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j, 2.+0.j, 3.+0.j])
Data-type consisting of more than one element:
>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])
Creating an array from sub-classes:
>>> np.array(np.asmatrix('1 2; 3 4'))
array([[1, 2],
[3, 4]])
>>> np.array(np.asmatrix('1 2; 3 4'), subok=True)
matrix([[1, 2],
[3, 4]])
numpy.array2string
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', prefix='', style=<no value>, formatter=None, threshold=None, edgeitems=None, sign=None, floatmode=None, suffix='', *, legacy=None)
Return a string representation of an array.
Parameters
----------
a : ndarray
Input array.
max_line_width : int, optional
Inserts newlines if text is longer than `max_line_width`.
Defaults to ``numpy.get_printoptions()['linewidth']``.
precision : int or None, optional
Floating point precision.
Defaults to ``numpy.get_printoptions()['precision']``.
suppress_small : bool, optional
Represent numbers "very close" to zero as zero; default is False.
Very close is defined by precision: if the precision is 8, e.g.,
numbers smaller (in absolute value) than 5e-9 are represented as
zero.
Defaults to ``numpy.get_printoptions()['suppress']``.
separator : str, optional
Inserted between elements.
prefix : str, optional
suffix : str, optional
The length of the prefix and suffix strings are used to respectively
align and wrap the output. An array is typically printed as::
prefix + array2string(a) + suffix
The output is left-padded by the length of the prefix string, and
wrapping is forced at the column ``max_line_width - len(suffix)``.
It should be noted that the content of prefix and suffix strings are
not included in the output.
style : _NoValue, optional
Has no effect, do not use.
.. deprecated:: 1.14.0
formatter : dict of callables, optional
If not None, the keys should indicate the type(s) that the respective
formatting function applies to. Callables should return a string.
Types that are not specified (by their corresponding keys) are handled
by the default formatters. Individual types for which a formatter
can be set are:
- 'bool'
- 'int'
- 'timedelta' : a `numpy.timedelta64`
- 'datetime' : a `numpy.datetime64`
- 'float'
- 'longfloat' : 128-bit floats
- 'complexfloat'
- 'longcomplexfloat' : composed of two 128-bit floats
- 'void' : type `numpy.void`
- 'numpystr' : types `numpy.bytes_` and `numpy.str_`
Other keys that can be used to set a group of types at once are:
- 'all' : sets all types
- 'int_kind' : sets 'int'
- 'float_kind' : sets 'float' and 'longfloat'
- 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
- 'str_kind' : sets 'numpystr'
threshold : int, optional
Total number of array elements which trigger summarization
rather than full repr.
Defaults to ``numpy.get_printoptions()['threshold']``.
edgeitems : int, optional
Number of array items in summary at beginning and end of
each dimension.
Defaults to ``numpy.get_printoptions()['edgeitems']``.
sign : string, either '-', '+', or ' ', optional
Controls printing of the sign of floating-point types. If '+', always
print the sign of positive values. If ' ', always prints a space
(whitespace character) in the sign position of positive values. If
'-', omit the sign character of positive values.
Defaults to ``numpy.get_printoptions()['sign']``.
.. versionchanged:: 2.0
The sign parameter can now be an integer type, previously
types were floating-point types.
floatmode : str, optional
Controls the interpretation of the `precision` option for
floating-point types.
Defaults to ``numpy.get_printoptions()['floatmode']``.
Can take the following values:
- 'fixed': Always print exactly `precision` fractional digits,
even if this would print more or fewer digits than
necessary to specify the value uniquely.
- 'unique': Print the minimum number of fractional digits necessary
to represent each value uniquely. Different elements may
have a different number of digits. The value of the
`precision` option is ignored.
- 'maxprec': Print at most `precision` fractional digits, but if
an element can be uniquely represented with fewer digits
only print it with that many.
- 'maxprec_equal': Print at most `precision` fractional digits,
but if every element in the array can be uniquely
represented with an equal number of fewer digits, use that
many digits for all elements.
legacy : string or `False`, optional
If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
approximates numpy 1.13 print output by including a space in the sign
position of floats and different behavior for 0d arrays. If set to
`False`, disables legacy mode. Unrecognized strings will be ignored
with a warning for forward compatibility.
.. versionadded:: 1.14.0
Returns
-------
array_str : str
String representation of the array.
Raises
------
TypeError
if a callable in `formatter` does not return a string.
See Also
--------
array_str, array_repr, set_printoptions, get_printoptions
Notes
-----
If a formatter is specified for a certain type, the `precision` keyword is
ignored for that type.
This is a very flexible function; `array_repr` and `array_str` are using
`array2string` internally so keywords with the same name should work
identically in all three functions.
Examples
--------
>>> import numpy as np
>>> x = np.array([1e-16,1,2,3])
>>> np.array2string(x, precision=2, separator=',',
... suppress_small=True)
'[0.,1.,2.,3.]'
>>> x = np.arange(3.)
>>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x})
'[0.00 1.00 2.00]'
>>> x = np.arange(3)
>>> np.array2string(x, formatter={'int':lambda x: hex(x)})
'[0x0 0x1 0x2]'
numpy.array_equal
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
array_equal(a1, a2, equal_nan=False)
True if two arrays have the same shape and elements, False otherwise.
Parameters
----------
a1, a2 : array_like
Input arrays.
equal_nan : bool
Whether to compare NaN's as equal. If the dtype of a1 and a2 is
complex, values will be considered equal if either the real or the
imaginary component of a given value is ``nan``.
.. versionadded:: 1.19.0
Returns
-------
b : bool
Returns True if the arrays are equal.
See Also
--------
allclose: Returns True if two arrays are element-wise equal within a
tolerance.
array_equiv: Returns True if input arrays are shape consistent and all
elements equal.
Examples
--------
>>> import numpy as np
>>> np.array_equal([1, 2], [1, 2])
True
>>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
>>> np.array_equal([1, 2], [1, 2, 3])
False
>>> np.array_equal([1, 2], [1, 4])
False
>>> a = np.array([1, np.nan])
>>> np.array_equal(a, a)
False
>>> np.array_equal(a, a, equal_nan=True)
True
When ``equal_nan`` is True, complex values with nan components are
considered equal if either the real *or* the imaginary components are nan.
>>> a = np.array([1 + 1j])
>>> b = a.copy()
>>> a.real = np.nan
>>> b.imag = np.nan
>>> np.array_equal(a, b, equal_nan=True)
True
numpy.array_equiv
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
array_equiv(a1, a2)
Returns True if input arrays are shape consistent and all elements equal.
Shape consistent means they are either the same shape, or one input array
can be broadcasted to create the same shape as the other one.
Parameters
----------
a1, a2 : array_like
Input arrays.
Returns
-------
out : bool
True if equivalent, False otherwise.
Examples
--------
>>> import numpy as np
>>> np.array_equiv([1, 2], [1, 2])
True
>>> np.array_equiv([1, 2], [1, 3])
False
Showing the shape equivalence:
>>> np.array_equiv([1, 2], [[1, 2], [1, 2]])
True
>>> np.array_equiv([1, 2], [[1, 2, 1, 2], [1, 2, 1, 2]])
False
>>> np.array_equiv([1, 2], [[1, 2], [1, 3]])
False
numpy.array_repr
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
array_repr(arr, max_line_width=None, precision=None, suppress_small=None)
Return the string representation of an array.
Parameters
----------
arr : ndarray
Input array.
max_line_width : int, optional
Inserts newlines if text is longer than `max_line_width`.
Defaults to ``numpy.get_printoptions()['linewidth']``.
precision : int, optional
Floating point precision.
Defaults to ``numpy.get_printoptions()['precision']``.
suppress_small : bool, optional
Represent numbers "very close" to zero as zero; default is False.
Very close is defined by precision: if the precision is 8, e.g.,
numbers smaller (in absolute value) than 5e-9 are represented as
zero.
Defaults to ``numpy.get_printoptions()['suppress']``.
Returns
-------
string : str
The string representation of an array.
See Also
--------
array_str, array2string, set_printoptions
Examples
--------
>>> import numpy as np
>>> np.array_repr(np.array([1,2]))
'array([1, 2])'
>>> np.array_repr(np.ma.array([0.]))
'MaskedArray([0.])'
>>> np.array_repr(np.array([], np.int32))
'array([], dtype=int32)'
>>> x = np.array([1e-6, 4e-7, 2, 3])
>>> np.array_repr(x, precision=6, suppress_small=True)
'array([0.000001, 0. , 2. , 3. ])'
numpy.array_split
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
array_split(ary, indices_or_sections, axis=0)
Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis. For an array of length l that should be split
into n sections, it returns l % n sub-arrays of size l//n + 1
and the rest of size l//n.
See Also
--------
split : Split array into multiple sub-arrays of equal size.
Examples
--------
>>> import numpy as np
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7.])]
>>> x = np.arange(9)
>>> np.array_split(x, 4)
[array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]
numpy.array_str
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
array_str(a, max_line_width=None, precision=None, suppress_small=None)
Return a string representation of the data in an array.
The data in the array is returned as a single string. This function is
similar to `array_repr`, the difference being that `array_repr` also
returns information on the kind of array and its data type.
Parameters
----------
a : ndarray
Input array.
max_line_width : int, optional
Inserts newlines if text is longer than `max_line_width`.
Defaults to ``numpy.get_printoptions()['linewidth']``.
precision : int, optional
Floating point precision.
Defaults to ``numpy.get_printoptions()['precision']``.
suppress_small : bool, optional
Represent numbers "very close" to zero as zero; default is False.
Very close is defined by precision: if the precision is 8, e.g.,
numbers smaller (in absolute value) than 5e-9 are represented as
zero.
Defaults to ``numpy.get_printoptions()['suppress']``.
See Also
--------
array2string, array_repr, set_printoptions
Examples
--------
>>> import numpy as np
>>> np.array_str(np.arange(3))
'[0 1 2]'
numpy.asanyarray
Python Library Documentation: built-in function asanyarray in module numpy
asanyarray(...)
asanyarray(a, dtype=None, order=None, *, like=None)
Convert the input to an ndarray, but pass ndarray subclasses through.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes scalars, lists, lists of tuples, tuples, tuples of tuples,
tuples of lists, and ndarrays.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F', 'A', 'K'}, optional
Memory layout. 'A' and 'K' depend on the order of input array a.
'C' row-major (C-style),
'F' column-major (Fortran-style) memory representation.
'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
'K' (keep) preserve input order
Defaults to 'C'.
device : str, optional
The device on which to place the created array. Default: ``None``.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.1.0
copy : bool, optional
If ``True``, then the object is copied. If ``None`` then the object is
copied only if needed, i.e. if ``__array__`` returns a copy, if obj
is a nested sequence, or if a copy is needed to satisfy any of
the other requirements (``dtype``, ``order``, etc.).
For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
Default: ``None``.
.. versionadded:: 2.1.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray or an ndarray subclass
Array interpretation of `a`. If `a` is an ndarray or a subclass
of ndarray, it is returned as-is and no copy is performed.
See Also
--------
asarray : Similar function which always returns ndarrays.
ascontiguousarray : Convert input to a contiguous array.
asfortranarray : Convert input to an ndarray with column-major
memory order.
asarray_chkfinite : Similar function which checks input for NaNs and
Infs.
fromiter : Create an array from an iterator.
fromfunction : Construct an array by executing a function on grid
positions.
Examples
--------
Convert a list into an array:
>>> a = [1, 2]
>>> import numpy as np
>>> np.asanyarray(a)
array([1, 2])
Instances of `ndarray` subclasses are passed through as-is:
>>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray)
>>> np.asanyarray(a) is a
True
numpy.asarray
Python Library Documentation: built-in function asarray in module numpy
asarray(...)
asarray(a, dtype=None, order=None, *, device=None, copy=None, like=None)
Convert the input to an array.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F', 'A', 'K'}, optional
Memory layout. 'A' and 'K' depend on the order of input array a.
'C' row-major (C-style),
'F' column-major (Fortran-style) memory representation.
'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
'K' (keep) preserve input order
Defaults to 'K'.
device : str, optional
The device on which to place the created array. Default: ``None``.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
copy : bool, optional
If ``True``, then the object is copied. If ``None`` then the object is
copied only if needed, i.e. if ``__array__`` returns a copy, if obj
is a nested sequence, or if a copy is needed to satisfy any of
the other requirements (``dtype``, ``order``, etc.).
For ``False`` it raises a ``ValueError`` if a copy cannot be avoided.
Default: ``None``.
.. versionadded:: 2.0.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
Array interpretation of ``a``. No copy is performed if the input
is already an ndarray with matching dtype and order. If ``a`` is a
subclass of ndarray, a base class ndarray is returned.
See Also
--------
asanyarray : Similar function which passes through subclasses.
ascontiguousarray : Convert input to a contiguous array.
asfortranarray : Convert input to an ndarray with column-major
memory order.
asarray_chkfinite : Similar function which checks input for NaNs and Infs.
fromiter : Create an array from an iterator.
fromfunction : Construct an array by executing a function on grid
positions.
Examples
--------
Convert a list into an array:
>>> a = [1, 2]
>>> import numpy as np
>>> np.asarray(a)
array([1, 2])
Existing arrays are not copied:
>>> a = np.array([1, 2])
>>> np.asarray(a) is a
True
If `dtype` is set, array is copied only if dtype does not match:
>>> a = np.array([1, 2], dtype=np.float32)
>>> np.shares_memory(np.asarray(a, dtype=np.float32), a)
True
>>> np.shares_memory(np.asarray(a, dtype=np.float64), a)
False
Contrary to `asanyarray`, ndarray subclasses are not passed through:
>>> issubclass(np.recarray, np.ndarray)
True
>>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray)
>>> np.asarray(a) is a
False
>>> np.asanyarray(a) is a
True
numpy.asarray_chkfinite
Python Library Documentation: function asarray_chkfinite in module numpy
asarray_chkfinite(a, dtype=None, order=None)
Convert the input to an array, checking for NaNs or Infs.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays. Success requires no NaNs or Infs.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F', 'A', 'K'}, optional
Memory layout. 'A' and 'K' depend on the order of input array a.
'C' row-major (C-style),
'F' column-major (Fortran-style) memory representation.
'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
'K' (keep) preserve input order
Defaults to 'C'.
Returns
-------
out : ndarray
Array interpretation of `a`. No copy is performed if the input
is already an ndarray. If `a` is a subclass of ndarray, a base
class ndarray is returned.
Raises
------
ValueError
Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity).
See Also
--------
asarray : Create and array.
asanyarray : Similar function which passes through subclasses.
ascontiguousarray : Convert input to a contiguous array.
asfortranarray : Convert input to an ndarray with column-major
memory order.
fromiter : Create an array from an iterator.
fromfunction : Construct an array by executing a function on grid
positions.
Examples
--------
>>> import numpy as np
Convert a list into an array. If all elements are finite, then
``asarray_chkfinite`` is identical to ``asarray``.
>>> a = [1, 2]
>>> np.asarray_chkfinite(a, dtype=float)
array([1., 2.])
Raises ValueError if array_like contains Nans or Infs.
>>> a = [1, 2, np.inf]
>>> try:
... np.asarray_chkfinite(a)
... except ValueError:
... print('ValueError')
...
ValueError
numpy.ascontiguousarray
Python Library Documentation: built-in function ascontiguousarray in module numpy
ascontiguousarray(...)
ascontiguousarray(a, dtype=None, *, like=None)
Return a contiguous array (ndim >= 1) in memory (C order).
Parameters
----------
a : array_like
Input array.
dtype : str or dtype object, optional
Data-type of returned array.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
Contiguous array of same shape and content as `a`, with type `dtype`
if specified.
See Also
--------
asfortranarray : Convert input to an ndarray with column-major
memory order.
require : Return an ndarray that satisfies requirements.
ndarray.flags : Information about the memory layout of the array.
Examples
--------
Starting with a Fortran-contiguous array:
>>> import numpy as np
>>> x = np.ones((2, 3), order='F')
>>> x.flags['F_CONTIGUOUS']
True
Calling ``ascontiguousarray`` makes a C-contiguous copy:
>>> y = np.ascontiguousarray(x)
>>> y.flags['C_CONTIGUOUS']
True
>>> np.may_share_memory(x, y)
False
Now, starting with a C-contiguous array:
>>> x = np.ones((2, 3), order='C')
>>> x.flags['C_CONTIGUOUS']
True
Then, calling ``ascontiguousarray`` returns the same object:
>>> y = np.ascontiguousarray(x)
>>> x is y
True
Note: This function returns an array with at least one-dimension (1-d)
so it will not preserve 0-d arrays.
numpy.asfortranarray
Python Library Documentation: built-in function asfortranarray in module numpy
asfortranarray(...)
asfortranarray(a, dtype=None, *, like=None)
Return an array (ndim >= 1) laid out in Fortran order in memory.
Parameters
----------
a : array_like
Input array.
dtype : str or dtype object, optional
By default, the data-type is inferred from the input data.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
The input `a` in Fortran, or column-major, order.
See Also
--------
ascontiguousarray : Convert input to a contiguous (C order) array.
asanyarray : Convert input to an ndarray with either row or
column-major memory order.
require : Return an ndarray that satisfies requirements.
ndarray.flags : Information about the memory layout of the array.
Examples
--------
Starting with a C-contiguous array:
>>> import numpy as np
>>> x = np.ones((2, 3), order='C')
>>> x.flags['C_CONTIGUOUS']
True
Calling ``asfortranarray`` makes a Fortran-contiguous copy:
>>> y = np.asfortranarray(x)
>>> y.flags['F_CONTIGUOUS']
True
>>> np.may_share_memory(x, y)
False
Now, starting with a Fortran-contiguous array:
>>> x = np.ones((2, 3), order='F')
>>> x.flags['F_CONTIGUOUS']
True
Then, calling ``asfortranarray`` returns the same object:
>>> y = np.asfortranarray(x)
>>> x is y
True
Note: This function returns an array with at least one-dimension (1-d)
so it will not preserve 0-d arrays.
numpy.asin
Python Library Documentation: ufunc
arcsin = <ufunc 'arcsin'>
arcsin(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse sine, element-wise.
Parameters
----------
x : array_like
`y`-coordinate on the unit circle.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
angle : ndarray
The inverse sine of each element in `x`, in radians and in the
closed interval ``[-pi/2, pi/2]``.
This is a scalar if `x` is a scalar.
See Also
--------
sin, cos, arccos, tan, arctan, arctan2, emath.arcsin
Notes
-----
`arcsin` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that :math:`sin(z) = x`. The convention is to
return the angle `z` whose real part lies in [-pi/2, pi/2].
For real-valued input data types, *arcsin* always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arcsin` is a complex analytic function that
has, by convention, the branch cuts [-inf, -1] and [1, inf] and is
continuous from above on the former and from below on the latter.
The inverse sine is also known as `asin` or sin^{-1}.
References
----------
Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*,
10th printing, New York: Dover, 1964, pp. 79ff.
https://personal.math.ubc.ca/~cbm/aands/page_79.htm
Examples
--------
>>> import numpy as np
>>> np.arcsin(1) # pi/2
1.5707963267948966
>>> np.arcsin(-1) # -pi/2
-1.5707963267948966
>>> np.arcsin(0)
0.0
numpy.asinh
Python Library Documentation: ufunc
arcsinh = <ufunc 'arcsinh'>
arcsinh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse hyperbolic sine element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
Notes
-----
`arcsinh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `sinh(z) = x`. The convention is to return the
`z` whose imaginary part lies in `[-pi/2, pi/2]`.
For real-valued input data types, `arcsinh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
returns ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arcsinh` is a complex analytical function that
has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from
the right on the former and from the left on the latter.
The inverse hyperbolic sine is also known as `asinh` or ``sinh^-1``.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86.
https://personal.math.ubc.ca/~cbm/aands/page_86.htm
.. [2] Wikipedia, "Inverse hyperbolic function",
https://en.wikipedia.org/wiki/Arcsinh
Examples
--------
>>> import numpy as np
>>> np.arcsinh(np.array([np.e, 10.0]))
array([ 1.72538256, 2.99822295])
numpy.asmatrix
Python Library Documentation: function asmatrix in module numpy
asmatrix(data, dtype=None)
Interpret the input as a matrix.
Unlike `matrix`, `asmatrix` does not make a copy if the input is already
a matrix or an ndarray. Equivalent to ``matrix(data, copy=False)``.
Parameters
----------
data : array_like
Input data.
dtype : data-type
Data-type of the output matrix.
Returns
-------
mat : matrix
`data` interpreted as a matrix.
Examples
--------
>>> import numpy as np
>>> x = np.array([[1, 2], [3, 4]])
>>> m = np.asmatrix(x)
>>> x[0,0] = 5
>>> m
matrix([[5, 2],
[3, 4]])
numpy.astype
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
astype(x, dtype, /, *, copy=True, device=None)
Copies an array to a specified data type.
This function is an Array API compatible alternative to
`numpy.ndarray.astype`.
Parameters
----------
x : ndarray
Input NumPy array to cast. ``array_likes`` are explicitly not
supported here.
dtype : dtype
Data type of the result.
copy : bool, optional
Specifies whether to copy an array when the specified dtype matches
the data type of the input array ``x``. If ``True``, a newly allocated
array must always be returned. If ``False`` and the specified dtype
matches the data type of the input array, the input array must be
returned; otherwise, a newly allocated array must be returned.
Defaults to ``True``.
device : str, optional
The device on which to place the returned array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.1.0
Returns
-------
out : ndarray
An array having the specified data type.
See Also
--------
ndarray.astype
Examples
--------
>>> import numpy as np
>>> arr = np.array([1, 2, 3]); arr
array([1, 2, 3])
>>> np.astype(arr, np.float64)
array([1., 2., 3.])
Non-copy case:
>>> arr = np.array([1, 2, 3])
>>> arr_noncpy = np.astype(arr, arr.dtype, copy=False)
>>> np.shares_memory(arr, arr_noncpy)
True
numpy.atan
Python Library Documentation: ufunc
arctan = <ufunc 'arctan'>
arctan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Trigonometric inverse tangent, element-wise.
The inverse of tan, so that if ``y = tan(x)`` then ``x = arctan(y)``.
Parameters
----------
x : array_like
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Out has the same shape as `x`. Its real part is in
``[-pi/2, pi/2]`` (``arctan(+/-inf)`` returns ``+/-pi/2``).
This is a scalar if `x` is a scalar.
See Also
--------
arctan2 : The "four quadrant" arctan of the angle formed by (`x`, `y`)
and the positive `x`-axis.
angle : Argument of complex values.
Notes
-----
`arctan` is a multi-valued function: for each `x` there are infinitely
many numbers `z` such that tan(`z`) = `x`. The convention is to return
the angle `z` whose real part lies in [-pi/2, pi/2].
For real-valued input data types, `arctan` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arctan` is a complex analytic function that
has [``1j, infj``] and [``-1j, -infj``] as branch cuts, and is continuous
from the left on the former and from the right on the latter.
The inverse tangent is also known as `atan` or tan^{-1}.
References
----------
Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*,
10th printing, New York: Dover, 1964, pp. 79.
https://personal.math.ubc.ca/~cbm/aands/page_79.htm
Examples
--------
We expect the arctan of 0 to be 0, and of 1 to be pi/4:
>>> import numpy as np
>>> np.arctan([0, 1])
array([ 0. , 0.78539816])
>>> np.pi/4
0.78539816339744828
Plot arctan:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-10, 10)
>>> plt.plot(x, np.arctan(x))
>>> plt.axis('tight')
>>> plt.show()
numpy.atan2
Python Library Documentation: ufunc
arctan2 = <ufunc 'arctan2'>
arctan2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly.
The quadrant (i.e., branch) is chosen so that ``arctan2(x1, x2)`` is
the signed angle in radians between the ray ending at the origin and
passing through the point (1,0), and the ray ending at the origin and
passing through the point (`x2`, `x1`). (Note the role reversal: the
"`y`-coordinate" is the first function parameter, the "`x`-coordinate"
is the second.) By IEEE convention, this function is defined for
`x2` = +/-0 and for either or both of `x1` and `x2` = +/-inf (see
Notes for specific values).
This function is not defined for complex-valued arguments; for the
so-called argument of complex values, use `angle`.
Parameters
----------
x1 : array_like, real-valued
`y`-coordinates.
x2 : array_like, real-valued
`x`-coordinates.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
angle : ndarray
Array of angles in radians, in the range ``[-pi, pi]``.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
arctan, tan, angle
Notes
-----
*arctan2* is identical to the `atan2` function of the underlying
C library. The following special values are defined in the C
standard: [1]_
====== ====== ================
`x1` `x2` `arctan2(x1,x2)`
====== ====== ================
+/- 0 +0 +/- 0
+/- 0 -0 +/- pi
> 0 +/-inf +0 / +pi
< 0 +/-inf -0 / -pi
+/-inf +inf +/- (pi/4)
+/-inf -inf +/- (3*pi/4)
====== ====== ================
Note that +0 and -0 are distinct floating point numbers, as are +inf
and -inf.
References
----------
.. [1] ISO/IEC standard 9899:1999, "Programming language C."
Examples
--------
Consider four points in different quadrants:
>>> import numpy as np
>>> x = np.array([-1, +1, +1, -1])
>>> y = np.array([-1, -1, +1, +1])
>>> np.arctan2(y, x) * 180 / np.pi
array([-135., -45., 45., 135.])
Note the order of the parameters. `arctan2` is defined also when `x2` = 0
and at several other special points, obtaining values in
the range ``[-pi, pi]``:
>>> np.arctan2([1., -1.], [0., 0.])
array([ 1.57079633, -1.57079633])
>>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf])
array([0. , 3.14159265, 0.78539816])
numpy.atanh
Python Library Documentation: ufunc
arctanh = <ufunc 'arctanh'>
arctanh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse hyperbolic tangent element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
See Also
--------
emath.arctanh
Notes
-----
`arctanh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that ``tanh(z) = x``. The convention is to return
the `z` whose imaginary part lies in `[-pi/2, pi/2]`.
For real-valued input data types, `arctanh` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arctanh` is a complex analytical function
that has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from
above on the former and from below on the latter.
The inverse hyperbolic tangent is also known as `atanh` or ``tanh^-1``.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86.
https://personal.math.ubc.ca/~cbm/aands/page_86.htm
.. [2] Wikipedia, "Inverse hyperbolic function",
https://en.wikipedia.org/wiki/Arctanh
Examples
--------
>>> import numpy as np
>>> np.arctanh([0, -0.5])
array([ 0. , -0.54930614])
numpy.atleast_1d
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
atleast_1d(*arys)
Convert inputs to arrays with at least one dimension.
Scalar inputs are converted to 1-dimensional arrays, whilst
higher-dimensional inputs are preserved.
Parameters
----------
arys1, arys2, ... : array_like
One or more input arrays.
Returns
-------
ret : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 1``.
Copies are made only if necessary.
See Also
--------
atleast_2d, atleast_3d
Examples
--------
>>> import numpy as np
>>> np.atleast_1d(1.0)
array([1.])
>>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array([[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]])
>>> np.atleast_1d(x) is x
True
>>> np.atleast_1d(1, [3, 4])
(array([1]), array([3, 4]))
numpy.atleast_2d
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
atleast_2d(*arys)
View inputs as arrays with at least two dimensions.
Parameters
----------
arys1, arys2, ... : array_like
One or more array-like sequences. Non-array inputs are converted
to arrays. Arrays that already have two or more dimensions are
preserved.
Returns
-------
res, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 2``.
Copies are avoided where possible, and views with two or more
dimensions are returned.
See Also
--------
atleast_1d, atleast_3d
Examples
--------
>>> import numpy as np
>>> np.atleast_2d(3.0)
array([[3.]])
>>> x = np.arange(3.0)
>>> np.atleast_2d(x)
array([[0., 1., 2.]])
>>> np.atleast_2d(x).base is x
True
>>> np.atleast_2d(1, [1, 2], [[1, 2]])
(array([[1]]), array([[1, 2]]), array([[1, 2]]))
numpy.atleast_3d
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
atleast_3d(*arys)
View inputs as arrays with at least three dimensions.
Parameters
----------
arys1, arys2, ... : array_like
One or more array-like sequences. Non-array inputs are converted to
arrays. Arrays that already have three or more dimensions are
preserved.
Returns
-------
res1, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are
avoided where possible, and views with three or more dimensions are
returned. For example, a 1-D array of shape ``(N,)`` becomes a view
of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a
view of shape ``(M, N, 1)``.
See Also
--------
atleast_1d, atleast_2d
Examples
--------
>>> import numpy as np
>>> np.atleast_3d(3.0)
array([[[3.]]])
>>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)
>>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> np.atleast_3d(x).base is x.base # x is a reshape, so not base itself
True
>>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
... print(arr, arr.shape) # doctest: +SKIP
...
[[[1]
[2]]] (1, 2, 1)
[[[1]
[2]]] (1, 2, 1)
[[[1 2]]] (1, 1, 2)
numpy.average
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
average(a, axis=None, weights=None, returned=False, *, keepdims=<no value>)
Compute the weighted average along the specified axis.
Parameters
----------
a : array_like
Array containing data to be averaged. If `a` is not an array, a
conversion is attempted.
axis : None or int or tuple of ints, optional
Axis or axes along which to average `a`. The default,
`axis=None`, will average over all of the elements of the input array.
If axis is negative it counts from the last to the first axis.
.. versionadded:: 1.7.0
If axis is a tuple of ints, averaging is performed on all of the axes
specified in the tuple instead of a single axis or all the axes as
before.
weights : array_like, optional
An array of weights associated with the values in `a`. Each value in
`a` contributes to the average according to its associated weight.
The array of weights must be the same shape as `a` if no axis is
specified, otherwise the weights must have dimensions and shape
consistent with `a` along the specified axis.
If `weights=None`, then all data in `a` are assumed to have a
weight equal to one.
The calculation is::
avg = sum(a * weights) / sum(weights)
where the sum is over all included elements.
The only constraint on the values of `weights` is that `sum(weights)`
must not be 0.
returned : bool, optional
Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`)
is returned, otherwise only the average is returned.
If `weights=None`, `sum_of_weights` is equivalent to the number of
elements over which the average is taken.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
*Note:* `keepdims` will not work with instances of `numpy.matrix`
or other classes whose methods do not support `keepdims`.
.. versionadded:: 1.23.0
Returns
-------
retval, [sum_of_weights] : array_type or double
Return the average along the specified axis. When `returned` is `True`,
return a tuple with the average as the first element and the sum
of the weights as the second element. `sum_of_weights` is of the
same type as `retval`. The result dtype follows a general pattern.
If `weights` is None, the result dtype will be that of `a` , or ``float64``
if `a` is integral. Otherwise, if `weights` is not None and `a` is non-
integral, the result type will be the type of lowest precision capable of
representing values of both `a` and `weights`. If `a` happens to be
integral, the previous rules still applies but the result dtype will
at least be ``float64``.
Raises
------
ZeroDivisionError
When all weights along axis are zero. See `numpy.ma.average` for a
version robust to this type of error.
TypeError
When `weights` does not have the same shape as `a`, and `axis=None`.
ValueError
When `weights` does not have dimensions and shape consistent with `a`
along specified `axis`.
See Also
--------
mean
ma.average : average for masked arrays -- useful if your data contains
"missing" values
numpy.result_type : Returns the type that results from applying the
numpy type promotion rules to the arguments.
Examples
--------
>>> import numpy as np
>>> data = np.arange(1, 5)
>>> data
array([1, 2, 3, 4])
>>> np.average(data)
2.5
>>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1))
4.0
>>> data = np.arange(6).reshape((3, 2))
>>> data
array([[0, 1],
[2, 3],
[4, 5]])
>>> np.average(data, axis=1, weights=[1./4, 3./4])
array([0.75, 2.75, 4.75])
>>> np.average(data, weights=[1./4, 3./4])
Traceback (most recent call last):
...
TypeError: Axis must be specified when shapes of a and weights differ.
With ``keepdims=True``, the following result has shape (3, 1).
>>> np.average(data, axis=1, keepdims=True)
array([[0.5],
[2.5],
[4.5]])
>>> data = np.arange(8).reshape((2, 2, 2))
>>> data
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.average(data, axis=(0, 1), weights=[[1./4, 3./4], [1., 1./2]])
array([3.4, 4.4])
>>> np.average(data, axis=0, weights=[[1./4, 3./4], [1., 1./2]])
Traceback (most recent call last):
...
ValueError: Shape of weights must be consistent
with shape of a along specified axis.
numpy.bartlett
Python Library Documentation: function bartlett in module numpy
bartlett(M)
Return the Bartlett window.
The Bartlett window is very similar to a triangular window, except
that the end points are at zero. It is often used in signal
processing for tapering a signal, without generating too much
ripple in the frequency domain.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : array
The triangular window, with the maximum value normalized to one
(the value one appears only if the number of samples is odd), with
the first and last samples equal to zero.
See Also
--------
blackman, hamming, hanning, kaiser
Notes
-----
The Bartlett window is defined as
.. math:: w(n) = \frac{2}{M-1} \left(
\frac{M-1}{2} - \left|n - \frac{M-1}{2}\right|
\right)
Most references to the Bartlett window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. Note that convolution with this window produces linear
interpolation. It is also known as an apodization (which means "removing
the foot", i.e. smoothing discontinuities at the beginning and end of the
sampled signal) or tapering function. The Fourier transform of the
Bartlett window is the product of two sinc functions. Note the excellent
discussion in Kanasewich [2]_.
References
----------
.. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
Biometrika 37, 1-16, 1950.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 109-110.
.. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal
Processing", Prentice-Hall, 1999, pp. 468-471.
.. [4] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 429.
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> np.bartlett(12)
array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273, # may vary
0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636,
0.18181818, 0. ])
Plot the window and its frequency response (requires SciPy and matplotlib).
.. plot::
:include-source:
import matplotlib.pyplot as plt
from numpy.fft import fft, fftshift
window = np.bartlett(51)
plt.plot(window)
plt.title("Bartlett window")
plt.ylabel("Amplitude")
plt.xlabel("Sample")
plt.show()
plt.figure()
A = fft(window, 2048) / 25.5
mag = np.abs(fftshift(A))
freq = np.linspace(-0.5, 0.5, len(A))
with np.errstate(divide='ignore', invalid='ignore'):
response = 20 * np.log10(mag)
response = np.clip(response, -100, 100)
plt.plot(freq, response)
plt.title("Frequency response of Bartlett window")
plt.ylabel("Magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
plt.axis('tight')
plt.show()
numpy.base_repr
Python Library Documentation: function base_repr in module numpy
base_repr(number, base=2, padding=0)
Return a string representation of a number in the given base system.
Parameters
----------
number : int
The value to convert. Positive and negative values are handled.
base : int, optional
Convert `number` to the `base` number system. The valid range is 2-36,
the default value is 2.
padding : int, optional
Number of zeros padded on the left. Default is 0 (no padding).
Returns
-------
out : str
String representation of `number` in `base` system.
See Also
--------
binary_repr : Faster version of `base_repr` for base 2.
Examples
--------
>>> import numpy as np
>>> np.base_repr(5)
'101'
>>> np.base_repr(6, 5)
'11'
>>> np.base_repr(7, base=5, padding=3)
'00012'
>>> np.base_repr(10, base=16)
'A'
>>> np.base_repr(32, base=16)
'20'
numpy.binary_repr
Python Library Documentation: function binary_repr in module numpy
binary_repr(num, width=None)
Return the binary representation of the input number as a string.
For negative numbers, if width is not given, a minus sign is added to the
front. If width is given, the two's complement of the number is
returned, with respect to that width.
In a two's-complement system negative numbers are represented by the two's
complement of the absolute value. This is the most common method of
representing signed integers on computers [1]_. A N-bit two's-complement
system can represent every integer in the range
:math:`-2^{N-1}` to :math:`+2^{N-1}-1`.
Parameters
----------
num : int
Only an integer decimal number can be used.
width : int, optional
The length of the returned string if `num` is positive, or the length
of the two's complement if `num` is negative, provided that `width` is
at least a sufficient number of bits for `num` to be represented in
the designated form. If the `width` value is insufficient, an error is
raised.
Returns
-------
bin : str
Binary representation of `num` or two's complement of `num`.
See Also
--------
base_repr: Return a string representation of a number in the given base
system.
bin: Python's built-in binary representation generator of an integer.
Notes
-----
`binary_repr` is equivalent to using `base_repr` with base 2, but about 25x
faster.
References
----------
.. [1] Wikipedia, "Two's complement",
https://en.wikipedia.org/wiki/Two's_complement
Examples
--------
>>> import numpy as np
>>> np.binary_repr(3)
'11'
>>> np.binary_repr(-3)
'-11'
>>> np.binary_repr(3, width=4)
'0011'
The two's complement is returned when the input number is negative and
width is specified:
>>> np.binary_repr(-3, width=3)
'101'
>>> np.binary_repr(-3, width=5)
'11101'
numpy.bincount
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
bincount(...)
bincount(x, /, weights=None, minlength=0)
Count number of occurrences of each value in array of non-negative ints.
The number of bins (of size 1) is one larger than the largest value in
`x`. If `minlength` is specified, there will be at least this number
of bins in the output array (though it will be longer if necessary,
depending on the contents of `x`).
Each bin gives the number of occurrences of its index value in `x`.
If `weights` is specified the input array is weighted by it, i.e. if a
value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead
of ``out[n] += 1``.
Parameters
----------
x : array_like, 1 dimension, nonnegative ints
Input array.
weights : array_like, optional
Weights, array of the same shape as `x`.
minlength : int, optional
A minimum number of bins for the output array.
.. versionadded:: 1.6.0
Returns
-------
out : ndarray of ints
The result of binning the input array.
The length of `out` is equal to ``np.amax(x)+1``.
Raises
------
ValueError
If the input is not 1-dimensional, or contains elements with negative
values, or if `minlength` is negative.
TypeError
If the type of the input is float or complex.
See Also
--------
histogram, digitize, unique
Examples
--------
>>> import numpy as np
>>> np.bincount(np.arange(5))
array([1, 1, 1, 1, 1])
>>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
array([1, 3, 1, 1, 0, 0, 0, 1])
>>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
>>> np.bincount(x).size == np.amax(x)+1
True
The input array needs to be of integer dtype, otherwise a
TypeError is raised:
>>> np.bincount(np.arange(5, dtype=float))
Traceback (most recent call last):
...
TypeError: Cannot cast array data from dtype('float64') to dtype('int64')
according to the rule 'safe'
A possible use of ``bincount`` is to perform sums over
variable-size chunks of an array, using the ``weights`` keyword.
>>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
>>> x = np.array([0, 1, 1, 2, 2, 2])
>>> np.bincount(x, weights=w)
array([ 0.3, 0.7, 1.1])
numpy.bitwise_and
Python Library Documentation: ufunc
bitwise_and = <ufunc 'bitwise_and'>
bitwise_and(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the bit-wise AND of two arrays element-wise.
Computes the bit-wise AND of the underlying binary representation of
the integers in the input arrays. This ufunc implements the C/Python
operator ``&``.
Parameters
----------
x1, x2 : array_like
Only integer and boolean types are handled.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Result.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_and
bitwise_or
bitwise_xor
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
>>> import numpy as np
The number 13 is represented by ``00001101``. Likewise, 17 is
represented by ``00010001``. The bit-wise AND of 13 and 17 is
therefore ``000000001``, or 1:
>>> np.bitwise_and(13, 17)
1
>>> np.bitwise_and(14, 13)
12
>>> np.binary_repr(12)
'1100'
>>> np.bitwise_and([14,3], 13)
array([12, 1])
>>> np.bitwise_and([11,7], [4,25])
array([0, 1])
>>> np.bitwise_and(np.array([2,5,255]), np.array([3,14,16]))
array([ 2, 4, 16])
>>> np.bitwise_and([True, True], [False, True])
array([False, True])
The ``&`` operator can be used as a shorthand for ``np.bitwise_and`` on
ndarrays.
>>> x1 = np.array([2, 5, 255])
>>> x2 = np.array([3, 14, 16])
>>> x1 & x2
array([ 2, 4, 16])
numpy.bitwise_count
Python Library Documentation: ufunc
bitwise_count = <ufunc 'bitwise_count'>
bitwise_count(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Computes the number of 1-bits in the absolute value of ``x``.
Analogous to the builtin `int.bit_count` or ``popcount`` in C++.
Parameters
----------
x : array_like, unsigned int
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding number of 1-bits in the input.
Returns uint8 for all integer types
This is a scalar if `x` is a scalar.
References
----------
.. [1] https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
.. [2] Wikipedia, "Hamming weight",
https://en.wikipedia.org/wiki/Hamming_weight
.. [3] http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20(Ones%20Count)
Examples
--------
>>> import numpy as np
>>> np.bitwise_count(1023)
10
>>> a = np.array([2**i - 1 for i in range(16)])
>>> np.bitwise_count(a)
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
dtype=uint8)
numpy.bitwise_invert
Python Library Documentation: ufunc
invert = <ufunc 'invert'>
invert(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute bit-wise inversion, or bit-wise NOT, element-wise.
Computes the bit-wise NOT of the underlying binary representation of
the integers in the input arrays. This ufunc implements the C/Python
operator ``~``.
For signed integer inputs, the bit-wise NOT of the absolute value is
returned. In a two's-complement system, this operation effectively flips
all the bits, resulting in a representation that corresponds to the
negative of the input plus one. This is the most common method of
representing signed integers on computers [1]_. A N-bit two's-complement
system can represent every integer in the range :math:`-2^{N-1}` to
:math:`+2^{N-1}-1`.
Parameters
----------
x : array_like
Only integer and boolean types are handled.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Result.
This is a scalar if `x` is a scalar.
See Also
--------
bitwise_and, bitwise_or, bitwise_xor
logical_not
binary_repr :
Return the binary representation of the input number as a string.
Notes
-----
``numpy.bitwise_not`` is an alias for `invert`:
>>> np.bitwise_not is np.invert
True
References
----------
.. [1] Wikipedia, "Two's complement",
https://en.wikipedia.org/wiki/Two's_complement
Examples
--------
>>> import numpy as np
We've seen that 13 is represented by ``00001101``.
The invert or bit-wise NOT of 13 is then:
>>> x = np.invert(np.array(13, dtype=np.uint8))
>>> x
242
>>> np.binary_repr(x, width=8)
'11110010'
The result depends on the bit-width:
>>> x = np.invert(np.array(13, dtype=np.uint16))
>>> x
65522
>>> np.binary_repr(x, width=16)
'1111111111110010'
When using signed integer types, the result is the bit-wise NOT of
the unsigned type, interpreted as a signed integer:
>>> np.invert(np.array([13], dtype=np.int8))
array([-14], dtype=int8)
>>> np.binary_repr(-14, width=8)
'11110010'
Booleans are accepted as well:
>>> np.invert(np.array([True, False]))
array([False, True])
The ``~`` operator can be used as a shorthand for ``np.invert`` on
ndarrays.
>>> x1 = np.array([True, False])
>>> ~x1
array([False, True])
numpy.bitwise_left_shift
Python Library Documentation: ufunc
left_shift = <ufunc 'left_shift'>
left_shift(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Shift the bits of an integer to the left.
Bits are shifted to the left by appending `x2` 0s at the right of `x1`.
Since the internal representation of numbers is in binary format, this
operation is equivalent to multiplying `x1` by ``2**x2``.
Parameters
----------
x1 : array_like of integer type
Input values.
x2 : array_like of integer type
Number of zeros to append to `x1`. Has to be non-negative.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : array of integer type
Return `x1` with bits shifted `x2` times to the left.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
right_shift : Shift the bits of an integer to the right.
binary_repr : Return the binary representation of the input number
as a string.
Examples
--------
>>> import numpy as np
>>> np.binary_repr(5)
'101'
>>> np.left_shift(5, 2)
20
>>> np.binary_repr(20)
'10100'
>>> np.left_shift(5, [1,2,3])
array([10, 20, 40])
Note that the dtype of the second argument may change the dtype of the
result and can lead to unexpected results in some cases (see
:ref:`Casting Rules <ufuncs.casting>`):
>>> a = np.left_shift(np.uint8(255), np.int64(1)) # Expect 254
>>> print(a, type(a)) # Unexpected result due to upcasting
510 <class 'numpy.int64'>
>>> b = np.left_shift(np.uint8(255), np.uint8(1))
>>> print(b, type(b))
254 <class 'numpy.uint8'>
The ``<<`` operator can be used as a shorthand for ``np.left_shift`` on
ndarrays.
>>> x1 = 5
>>> x2 = np.array([1, 2, 3])
>>> x1 << x2
array([10, 20, 40])
numpy.bitwise_not
Python Library Documentation: ufunc
invert = <ufunc 'invert'>
invert(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute bit-wise inversion, or bit-wise NOT, element-wise.
Computes the bit-wise NOT of the underlying binary representation of
the integers in the input arrays. This ufunc implements the C/Python
operator ``~``.
For signed integer inputs, the bit-wise NOT of the absolute value is
returned. In a two's-complement system, this operation effectively flips
all the bits, resulting in a representation that corresponds to the
negative of the input plus one. This is the most common method of
representing signed integers on computers [1]_. A N-bit two's-complement
system can represent every integer in the range :math:`-2^{N-1}` to
:math:`+2^{N-1}-1`.
Parameters
----------
x : array_like
Only integer and boolean types are handled.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Result.
This is a scalar if `x` is a scalar.
See Also
--------
bitwise_and, bitwise_or, bitwise_xor
logical_not
binary_repr :
Return the binary representation of the input number as a string.
Notes
-----
``numpy.bitwise_not`` is an alias for `invert`:
>>> np.bitwise_not is np.invert
True
References
----------
.. [1] Wikipedia, "Two's complement",
https://en.wikipedia.org/wiki/Two's_complement
Examples
--------
>>> import numpy as np
We've seen that 13 is represented by ``00001101``.
The invert or bit-wise NOT of 13 is then:
>>> x = np.invert(np.array(13, dtype=np.uint8))
>>> x
242
>>> np.binary_repr(x, width=8)
'11110010'
The result depends on the bit-width:
>>> x = np.invert(np.array(13, dtype=np.uint16))
>>> x
65522
>>> np.binary_repr(x, width=16)
'1111111111110010'
When using signed integer types, the result is the bit-wise NOT of
the unsigned type, interpreted as a signed integer:
>>> np.invert(np.array([13], dtype=np.int8))
array([-14], dtype=int8)
>>> np.binary_repr(-14, width=8)
'11110010'
Booleans are accepted as well:
>>> np.invert(np.array([True, False]))
array([False, True])
The ``~`` operator can be used as a shorthand for ``np.invert`` on
ndarrays.
>>> x1 = np.array([True, False])
>>> ~x1
array([False, True])
numpy.bitwise_or
Python Library Documentation: ufunc
bitwise_or = <ufunc 'bitwise_or'>
bitwise_or(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the bit-wise OR of two arrays element-wise.
Computes the bit-wise OR of the underlying binary representation of
the integers in the input arrays. This ufunc implements the C/Python
operator ``|``.
Parameters
----------
x1, x2 : array_like
Only integer and boolean types are handled.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Result.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_or
bitwise_and
bitwise_xor
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
>>> import numpy as np
The number 13 has the binary representation ``00001101``. Likewise,
16 is represented by ``00010000``. The bit-wise OR of 13 and 16 is
then ``00011101``, or 29:
>>> np.bitwise_or(13, 16)
29
>>> np.binary_repr(29)
'11101'
>>> np.bitwise_or(32, 2)
34
>>> np.bitwise_or([33, 4], 1)
array([33, 5])
>>> np.bitwise_or([33, 4], [1, 2])
array([33, 6])
>>> np.bitwise_or(np.array([2, 5, 255]), np.array([4, 4, 4]))
array([ 6, 5, 255])
>>> np.array([2, 5, 255]) | np.array([4, 4, 4])
array([ 6, 5, 255])
>>> np.bitwise_or(np.array([2, 5, 255, 2147483647], dtype=np.int32),
... np.array([4, 4, 4, 2147483647], dtype=np.int32))
array([ 6, 5, 255, 2147483647])
>>> np.bitwise_or([True, True], [False, True])
array([ True, True])
The ``|`` operator can be used as a shorthand for ``np.bitwise_or`` on
ndarrays.
>>> x1 = np.array([2, 5, 255])
>>> x2 = np.array([4, 4, 4])
>>> x1 | x2
array([ 6, 5, 255])
numpy.bitwise_right_shift
Python Library Documentation: ufunc
right_shift = <ufunc 'right_shift'>
right_shift(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Shift the bits of an integer to the right.
Bits are shifted to the right `x2`. Because the internal
representation of numbers is in binary format, this operation is
equivalent to dividing `x1` by ``2**x2``.
Parameters
----------
x1 : array_like, int
Input values.
x2 : array_like, int
Number of bits to remove at the right of `x1`.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray, int
Return `x1` with bits shifted `x2` times to the right.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
left_shift : Shift the bits of an integer to the left.
binary_repr : Return the binary representation of the input number
as a string.
Examples
--------
>>> import numpy as np
>>> np.binary_repr(10)
'1010'
>>> np.right_shift(10, 1)
5
>>> np.binary_repr(5)
'101'
>>> np.right_shift(10, [1,2,3])
array([5, 2, 1])
The ``>>`` operator can be used as a shorthand for ``np.right_shift`` on
ndarrays.
>>> x1 = 10
>>> x2 = np.array([1,2,3])
>>> x1 >> x2
array([5, 2, 1])
numpy.bitwise_xor
Python Library Documentation: ufunc
bitwise_xor = <ufunc 'bitwise_xor'>
bitwise_xor(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the bit-wise XOR of two arrays element-wise.
Computes the bit-wise XOR of the underlying binary representation of
the integers in the input arrays. This ufunc implements the C/Python
operator ``^``.
Parameters
----------
x1, x2 : array_like
Only integer and boolean types are handled.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Result.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_xor
bitwise_and
bitwise_or
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
>>> import numpy as np
The number 13 is represented by ``00001101``. Likewise, 17 is
represented by ``00010001``. The bit-wise XOR of 13 and 17 is
therefore ``00011100``, or 28:
>>> np.bitwise_xor(13, 17)
28
>>> np.binary_repr(28)
'11100'
>>> np.bitwise_xor(31, 5)
26
>>> np.bitwise_xor([31,3], 5)
array([26, 6])
>>> np.bitwise_xor([31,3], [5,6])
array([26, 5])
>>> np.bitwise_xor([True, True], [False, True])
array([ True, False])
The ``^`` operator can be used as a shorthand for ``np.bitwise_xor`` on
ndarrays.
>>> x1 = np.array([True, True])
>>> x2 = np.array([False, True])
>>> x1 ^ x2
array([ True, False])
numpy.blackman
Python Library Documentation: function blackman in module numpy
blackman(M)
Return the Blackman window.
The Blackman window is a taper formed by using the first three
terms of a summation of cosines. It was designed to have close to the
minimal leakage possible. It is close to optimal, only slightly worse
than a Kaiser window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
Returns
-------
out : ndarray
The window, with the maximum value normalized to one (the value one
appears only if the number of samples is odd).
See Also
--------
bartlett, hamming, hanning, kaiser
Notes
-----
The Blackman window is defined as
.. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)
Most references to the Blackman window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function. It is known as a
"near optimal" tapering function, almost as good (by some measures)
as the kaiser window.
References
----------
Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra,
Dover Publications, New York.
Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> np.blackman(12)
array([-1.38777878e-17, 3.26064346e-02, 1.59903635e-01, # may vary
4.14397981e-01, 7.36045180e-01, 9.67046769e-01,
9.67046769e-01, 7.36045180e-01, 4.14397981e-01,
1.59903635e-01, 3.26064346e-02, -1.38777878e-17])
Plot the window and the frequency response.
.. plot::
:include-source:
import matplotlib.pyplot as plt
from numpy.fft import fft, fftshift
window = np.blackman(51)
plt.plot(window)
plt.title("Blackman window")
plt.ylabel("Amplitude")
plt.xlabel("Sample")
plt.show() # doctest: +SKIP
plt.figure()
A = fft(window, 2048) / 25.5
mag = np.abs(fftshift(A))
freq = np.linspace(-0.5, 0.5, len(A))
with np.errstate(divide='ignore', invalid='ignore'):
response = 20 * np.log10(mag)
response = np.clip(response, -100, 100)
plt.plot(freq, response)
plt.title("Frequency response of Blackman window")
plt.ylabel("Magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
plt.axis('tight')
plt.show()
numpy.block
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
block(arrays)
Assemble an nd-array from nested lists of blocks.
Blocks in the innermost lists are concatenated (see `concatenate`) along
the last dimension (-1), then these are concatenated along the
second-last dimension (-2), and so on until the outermost list is reached.
Blocks can be of any dimension, but will not be broadcasted using
the normal rules. Instead, leading axes of size 1 are inserted,
to make ``block.ndim`` the same for all blocks. This is primarily useful
for working with scalars, and means that code like ``np.block([v, 1])``
is valid, where ``v.ndim == 1``.
When the nested list is two levels deep, this allows block matrices to be
constructed from their components.
.. versionadded:: 1.13.0
Parameters
----------
arrays : nested list of array_like or scalars (but not tuples)
If passed a single ndarray or scalar (a nested list of depth 0), this
is returned unmodified (and not copied).
Elements shapes must match along the appropriate axes (without
broadcasting), but leading 1s will be prepended to the shape as
necessary to make the dimensions match.
Returns
-------
block_array : ndarray
The array assembled from the given blocks.
The dimensionality of the output is equal to the greatest of:
* the dimensionality of all the inputs
* the depth to which the input list is nested
Raises
------
ValueError
* If list depths are mismatched - for instance, ``[[a, b], c]`` is
illegal, and should be spelt ``[[a, b], [c]]``
* If lists are empty - for instance, ``[[a, b], []]``
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
vstack : Stack arrays in sequence vertically (row wise).
hstack : Stack arrays in sequence horizontally (column wise).
dstack : Stack arrays in sequence depth wise (along third axis).
column_stack : Stack 1-D arrays as columns into a 2-D array.
vsplit : Split an array into multiple sub-arrays vertically (row-wise).
unstack : Split an array into a tuple of sub-arrays along an axis.
Notes
-----
When called with only scalars, ``np.block`` is equivalent to an ndarray
call. So ``np.block([[1, 2], [3, 4]])`` is equivalent to
``np.array([[1, 2], [3, 4]])``.
This function does not enforce that the blocks lie on a fixed grid.
``np.block([[a, b], [c, d]])`` is not restricted to arrays of the form::
AAAbb
AAAbb
cccDD
But is also allowed to produce, for some ``a, b, c, d``::
AAAbb
AAAbb
cDDDD
Since concatenation happens along the last axis first, `block` is *not*
capable of producing the following directly::
AAAbb
cccbb
cccDD
Matlab's "square bracket stacking", ``[A, B, ...; p, q, ...]``, is
equivalent to ``np.block([[A, B, ...], [p, q, ...]])``.
Examples
--------
The most common use of this function is to build a block matrix:
>>> import numpy as np
>>> A = np.eye(2) * 2
>>> B = np.eye(3) * 3
>>> np.block([
... [A, np.zeros((2, 3))],
... [np.ones((3, 2)), B ]
... ])
array([[2., 0., 0., 0., 0.],
[0., 2., 0., 0., 0.],
[1., 1., 3., 0., 0.],
[1., 1., 0., 3., 0.],
[1., 1., 0., 0., 3.]])
With a list of depth 1, `block` can be used as `hstack`:
>>> np.block([1, 2, 3]) # hstack([1, 2, 3])
array([1, 2, 3])
>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.block([a, b, 10]) # hstack([a, b, 10])
array([ 1, 2, 3, 4, 5, 6, 10])
>>> A = np.ones((2, 2), int)
>>> B = 2 * A
>>> np.block([A, B]) # hstack([A, B])
array([[1, 1, 2, 2],
[1, 1, 2, 2]])
With a list of depth 2, `block` can be used in place of `vstack`:
>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.block([[a], [b]]) # vstack([a, b])
array([[1, 2, 3],
[4, 5, 6]])
>>> A = np.ones((2, 2), int)
>>> B = 2 * A
>>> np.block([[A], [B]]) # vstack([A, B])
array([[1, 1],
[1, 1],
[2, 2],
[2, 2]])
It can also be used in place of `atleast_1d` and `atleast_2d`:
>>> a = np.array(0)
>>> b = np.array([1])
>>> np.block([a]) # atleast_1d(a)
array([0])
>>> np.block([b]) # atleast_1d(b)
array([1])
>>> np.block([[a]]) # atleast_2d(a)
array([[0]])
>>> np.block([[b]]) # atleast_2d(b)
array([[1]])
numpy.bmat
Python Library Documentation: function bmat in module numpy
bmat(obj, ldict=None, gdict=None)
Build a matrix object from a string, nested sequence, or array.
Parameters
----------
obj : str or array_like
Input data. If a string, variables in the current scope may be
referenced by name.
ldict : dict, optional
A dictionary that replaces local operands in current frame.
Ignored if `obj` is not a string or `gdict` is None.
gdict : dict, optional
A dictionary that replaces global operands in current frame.
Ignored if `obj` is not a string.
Returns
-------
out : matrix
Returns a matrix object, which is a specialized 2-D array.
See Also
--------
block :
A generalization of this function for N-d arrays, that returns normal
ndarrays.
Examples
--------
>>> import numpy as np
>>> A = np.asmatrix('1 1; 1 1')
>>> B = np.asmatrix('2 2; 2 2')
>>> C = np.asmatrix('3 4; 5 6')
>>> D = np.asmatrix('7 8; 9 0')
All the following expressions construct the same block matrix:
>>> np.bmat([[A, B], [C, D]])
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
>>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
>>> np.bmat('A,B; C,D')
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
numpy.bool
Python Library Documentation: class bool in module numpy class bool(generic) | Boolean type (True or False), stored as a byte. | | .. warning:: | | The :class:`bool` type is not a subclass of the :class:`int_` type | (the :class:`bool` is not even a number type). This is different | than Python's default implementation of :class:`bool` as a | sub-class of :class:`int`. | | :Character code: ``'?'`` | | Method resolution order: | bool | generic | builtins.object | | Methods defined here: | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __repr__(self, /) | Return repr(self). | | __ror__(self, value, /) | Return value|self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __xor__(self, value, /) | Return self^value. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.bool_
Python Library Documentation: class bool in module numpy class bool(generic) | Boolean type (True or False), stored as a byte. | | .. warning:: | | The :class:`bool` type is not a subclass of the :class:`int_` type | (the :class:`bool` is not even a number type). This is different | than Python's default implementation of :class:`bool` as a | sub-class of :class:`int`. | | :Character code: ``'?'`` | | Method resolution order: | bool | generic | builtins.object | | Methods defined here: | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __repr__(self, /) | Return repr(self). | | __ror__(self, value, /) | Return value|self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __xor__(self, value, /) | Return self^value. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.broadcast
Python Library Documentation: class broadcast in module numpy class broadcast(builtins.object) | Produce an object that mimics broadcasting. | | Parameters | ---------- | in1, in2, ... : array_like | Input parameters. | | Returns | ------- | b : broadcast object | Broadcast the input parameters against one another, and | return an object that encapsulates the result. | Amongst others, it has ``shape`` and ``nd`` properties, and | may be used as an iterator. | | See Also | -------- | broadcast_arrays | broadcast_to | broadcast_shapes | | Examples | -------- | | Manually adding two vectors, using broadcasting: | | >>> import numpy as np | >>> x = np.array([[1], [2], [3]]) | >>> y = np.array([4, 5, 6]) | >>> b = np.broadcast(x, y) | | >>> out = np.empty(b.shape) | >>> out.flat = [u+v for (u,v) in b] | >>> out | array([[5., 6., 7.], | [6., 7., 8.], | [7., 8., 9.]]) | | Compare against built-in broadcasting: | | >>> x + y | array([[5, 6, 7], | [6, 7, 8], | [7, 8, 9]]) | | Methods defined here: | | __iter__(self, /) | Implement iter(self). | | __next__(self, /) | Implement next(self). | | reset(...) | reset() | | Reset the broadcasted result's iterator(s). | | Parameters | ---------- | None | | Returns | ------- | None | | Examples | -------- | >>> import numpy as np | >>> x = np.array([1, 2, 3]) | >>> y = np.array([[4], [5], [6]]) | >>> b = np.broadcast(x, y) | >>> b.index | 0 | >>> next(b), next(b), next(b) | ((1, 4), (2, 4), (3, 4)) | >>> b.index | 3 | >>> b.reset() | >>> b.index | 0 | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | index | current index in broadcasted result | | Examples | -------- | | >>> import numpy as np | >>> x = np.array([[1], [2], [3]]) | >>> y = np.array([4, 5, 6]) | >>> b = np.broadcast(x, y) | >>> b.index | 0 | >>> next(b), next(b), next(b) | ((1, 4), (1, 5), (1, 6)) | >>> b.index | 3 | | iters | tuple of iterators along ``self``'s "components." | | Returns a tuple of `numpy.flatiter` objects, one for each "component" | of ``self``. | | See Also | -------- | numpy.flatiter | | Examples | -------- | | >>> import numpy as np | >>> x = np.array([1, 2, 3]) | >>> y = np.array([[4], [5], [6]]) | >>> b = np.broadcast(x, y) | >>> row, col = b.iters | >>> next(row), next(col) | (1, 4) | | nd | Number of dimensions of broadcasted result. For code intended for NumPy | 1.12.0 and later the more consistent `ndim` is preferred. | | Examples | -------- | >>> import numpy as np | >>> x = np.array([1, 2, 3]) | >>> y = np.array([[4], [5], [6]]) | >>> b = np.broadcast(x, y) | >>> b.nd | 2 | | ndim | Number of dimensions of broadcasted result. Alias for `nd`. | | .. versionadded:: 1.12.0 | | Examples | -------- | >>> import numpy as np | >>> x = np.array([1, 2, 3]) | >>> y = np.array([[4], [5], [6]]) | >>> b = np.broadcast(x, y) | >>> b.ndim | 2 | | numiter | Number of iterators possessed by the broadcasted result. | | Examples | -------- | >>> import numpy as np | >>> x = np.array([1, 2, 3]) | >>> y = np.array([[4], [5], [6]]) | >>> b = np.broadcast(x, y) | >>> b.numiter | 2 | | shape | Shape of broadcasted result. | | Examples | -------- | >>> import numpy as np | >>> x = np.array([1, 2, 3]) | >>> y = np.array([[4], [5], [6]]) | >>> b = np.broadcast(x, y) | >>> b.shape | (3, 3) | | size | Total size of broadcasted result. | | Examples | -------- | >>> import numpy as np | >>> x = np.array([1, 2, 3]) | >>> y = np.array([[4], [5], [6]]) | >>> b = np.broadcast(x, y) | >>> b.size | 9
numpy.broadcast_arrays
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
broadcast_arrays(*args, subok=False)
Broadcast any number of arrays against each other.
Parameters
----------
*args : array_likes
The arrays to broadcast.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned arrays will be forced to be a base-class array (default).
Returns
-------
broadcasted : tuple of arrays
These arrays are views on the original arrays. They are typically
not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location. If you need
to write to the arrays, make copies first. While you can set the
``writable`` flag True, writing to a single output value may end up
changing more than one location in the output array.
.. deprecated:: 1.17
The output is currently marked so that if written to, a deprecation
warning will be emitted. A future version will set the
``writable`` flag False so writing to it will raise an error.
See Also
--------
broadcast
broadcast_to
broadcast_shapes
Examples
--------
>>> import numpy as np
>>> x = np.array([[1,2,3]])
>>> y = np.array([[4],[5]])
>>> np.broadcast_arrays(x, y)
(array([[1, 2, 3],
[1, 2, 3]]),
array([[4, 4, 4],
[5, 5, 5]]))
Here is a useful idiom for getting contiguous copies instead of
non-contiguous views.
>>> [np.array(a) for a in np.broadcast_arrays(x, y)]
[array([[1, 2, 3],
[1, 2, 3]]),
array([[4, 4, 4],
[5, 5, 5]])]
numpy.broadcast_shapes
Python Library Documentation: function broadcast_shapes in module numpy
broadcast_shapes(*args)
Broadcast the input shapes into a single shape.
:ref:`Learn more about broadcasting here <basics.broadcasting>`.
.. versionadded:: 1.20.0
Parameters
----------
*args : tuples of ints, or ints
The shapes to be broadcast against each other.
Returns
-------
tuple
Broadcasted shape.
Raises
------
ValueError
If the shapes are not compatible and cannot be broadcast according
to NumPy's broadcasting rules.
See Also
--------
broadcast
broadcast_arrays
broadcast_to
Examples
--------
>>> import numpy as np
>>> np.broadcast_shapes((1, 2), (3, 1), (3, 2))
(3, 2)
>>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7))
(5, 6, 7)
numpy.broadcast_to
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
broadcast_to(array, shape, subok=False)
Broadcast an array to a new shape.
Parameters
----------
array : array_like
The array to broadcast.
shape : tuple or int
The shape of the desired array. A single integer ``i`` is interpreted
as ``(i,)``.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
Returns
-------
broadcast : array
A readonly view on the original array with the given shape. It is
typically not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location.
Raises
------
ValueError
If the array is not compatible with the new shape according to NumPy's
broadcasting rules.
See Also
--------
broadcast
broadcast_arrays
broadcast_shapes
Notes
-----
.. versionadded:: 1.10.0
Examples
--------
>>> import numpy as np
>>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
numpy.busday_count
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
busday_count(...)
busday_count(
begindates,
enddates,
weekmask='1111100',
holidays=[],
busdaycal=None,
out=None
)
Counts the number of valid days between `begindates` and
`enddates`, not including the day of `enddates`.
If ``enddates`` specifies a date value that is earlier than the
corresponding ``begindates`` date value, the count will be negative.
.. versionadded:: 1.7.0
Parameters
----------
begindates : array_like of datetime64[D]
The array of the first dates for counting.
enddates : array_like of datetime64[D]
The array of the end dates for counting, which are excluded
from the count themselves.
weekmask : str or array_like of bool, optional
A seven-element array indicating which of Monday through Sunday are
valid days. May be specified as a length-seven list or array, like
[1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
weekdays, optionally separated by white space. Valid abbreviations
are: Mon Tue Wed Thu Fri Sat Sun
holidays : array_like of datetime64[D], optional
An array of dates to consider as invalid dates. They may be
specified in any order, and NaT (not-a-time) dates are ignored.
This list is saved in a normalized form that is suited for
fast calculations of valid days.
busdaycal : busdaycalendar, optional
A `busdaycalendar` object which specifies the valid days. If this
parameter is provided, neither weekmask nor holidays may be
provided.
out : array of int, optional
If provided, this array is filled with the result.
Returns
-------
out : array of int
An array with a shape from broadcasting ``begindates`` and ``enddates``
together, containing the number of valid days between
the begin and end dates.
See Also
--------
busdaycalendar : An object that specifies a custom set of valid days.
is_busday : Returns a boolean array indicating valid days.
busday_offset : Applies an offset counted in valid days.
Examples
--------
>>> import numpy as np
>>> # Number of weekdays in January 2011
... np.busday_count('2011-01', '2011-02')
21
>>> # Number of weekdays in 2011
>>> np.busday_count('2011', '2012')
260
>>> # Number of Saturdays in 2011
... np.busday_count('2011', '2012', weekmask='Sat')
53
numpy.busday_offset
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
busday_offset(...)
busday_offset(
dates,
offsets,
roll='raise',
weekmask='1111100',
holidays=None,
busdaycal=None,
out=None
)
First adjusts the date to fall on a valid day according to
the ``roll`` rule, then applies offsets to the given dates
counted in valid days.
.. versionadded:: 1.7.0
Parameters
----------
dates : array_like of datetime64[D]
The array of dates to process.
offsets : array_like of int
The array of offsets, which is broadcast with ``dates``.
roll : {'raise', 'nat', 'forward', 'following', 'backward', 'preceding', 'modifiedfollowing', 'modifiedpreceding'}, optional
How to treat dates that do not fall on a valid day. The default
is 'raise'.
* 'raise' means to raise an exception for an invalid day.
* 'nat' means to return a NaT (not-a-time) for an invalid day.
* 'forward' and 'following' mean to take the first valid day
later in time.
* 'backward' and 'preceding' mean to take the first valid day
earlier in time.
* 'modifiedfollowing' means to take the first valid day
later in time unless it is across a Month boundary, in which
case to take the first valid day earlier in time.
* 'modifiedpreceding' means to take the first valid day
earlier in time unless it is across a Month boundary, in which
case to take the first valid day later in time.
weekmask : str or array_like of bool, optional
A seven-element array indicating which of Monday through Sunday are
valid days. May be specified as a length-seven list or array, like
[1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
weekdays, optionally separated by white space. Valid abbreviations
are: Mon Tue Wed Thu Fri Sat Sun
holidays : array_like of datetime64[D], optional
An array of dates to consider as invalid dates. They may be
specified in any order, and NaT (not-a-time) dates are ignored.
This list is saved in a normalized form that is suited for
fast calculations of valid days.
busdaycal : busdaycalendar, optional
A `busdaycalendar` object which specifies the valid days. If this
parameter is provided, neither weekmask nor holidays may be
provided.
out : array of datetime64[D], optional
If provided, this array is filled with the result.
Returns
-------
out : array of datetime64[D]
An array with a shape from broadcasting ``dates`` and ``offsets``
together, containing the dates with offsets applied.
See Also
--------
busdaycalendar : An object that specifies a custom set of valid days.
is_busday : Returns a boolean array indicating valid days.
busday_count : Counts how many valid days are in a half-open date range.
Examples
--------
>>> import numpy as np
>>> # First business day in October 2011 (not accounting for holidays)
... np.busday_offset('2011-10', 0, roll='forward')
np.datetime64('2011-10-03')
>>> # Last business day in February 2012 (not accounting for holidays)
... np.busday_offset('2012-03', -1, roll='forward')
np.datetime64('2012-02-29')
>>> # Third Wednesday in January 2011
... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed')
np.datetime64('2011-01-19')
>>> # 2012 Mother's Day in Canada and the U.S.
... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun')
np.datetime64('2012-05-13')
>>> # First business day on or after a date
... np.busday_offset('2011-03-20', 0, roll='forward')
np.datetime64('2011-03-21')
>>> np.busday_offset('2011-03-22', 0, roll='forward')
np.datetime64('2011-03-22')
>>> # First business day after a date
... np.busday_offset('2011-03-20', 1, roll='backward')
np.datetime64('2011-03-21')
>>> np.busday_offset('2011-03-22', 1, roll='backward')
np.datetime64('2011-03-23')
numpy.busdaycalendar
Python Library Documentation: class busdaycalendar in module numpy
class busdaycalendar(builtins.object)
| busdaycalendar(weekmask='1111100', holidays=None)
|
| A business day calendar object that efficiently stores information
| defining valid days for the busday family of functions.
|
| The default valid days are Monday through Friday ("business days").
| A busdaycalendar object can be specified with any set of weekly
| valid days, plus an optional "holiday" dates that always will be invalid.
|
| Once a busdaycalendar object is created, the weekmask and holidays
| cannot be modified.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| weekmask : str or array_like of bool, optional
| A seven-element array indicating which of Monday through Sunday are
| valid days. May be specified as a length-seven list or array, like
| [1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
| like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
| weekdays, optionally separated by white space. Valid abbreviations
| are: Mon Tue Wed Thu Fri Sat Sun
| holidays : array_like of datetime64[D], optional
| An array of dates to consider as invalid dates, no matter which
| weekday they fall upon. Holiday dates may be specified in any
| order, and NaT (not-a-time) dates are ignored. This list is
| saved in a normalized form that is suited for fast calculations
| of valid days.
|
| Returns
| -------
| out : busdaycalendar
| A business day calendar object containing the specified
| weekmask and holidays values.
|
| See Also
| --------
| is_busday : Returns a boolean array indicating valid days.
| busday_offset : Applies an offset counted in valid days.
| busday_count : Counts how many valid days are in a half-open date range.
|
| Attributes
| ----------
| weekmask : (copy) seven-element array of bool
| holidays : (copy) sorted array of datetime64[D]
|
| Notes
| -----
| Once a busdaycalendar object is created, you cannot modify the
| weekmask or holidays. The attributes return copies of internal data.
|
| Examples
| --------
| >>> import numpy as np
| >>> # Some important days in July
| ... bdd = np.busdaycalendar(
| ... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
| >>> # Default is Monday to Friday weekdays
| ... bdd.weekmask
| array([ True, True, True, True, True, False, False])
| >>> # Any holidays already on the weekend are removed
| ... bdd.holidays
| array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]')
|
| Methods defined here:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| holidays
| A copy of the holiday array indicating additional invalid days.
|
| weekmask
| A copy of the seven-element boolean mask indicating valid days.
numpy.byte
Python Library Documentation: class int8 in module numpy class int8(signedinteger) | Signed integer type, compatible with C ``char``. | | :Character code: ``'b'`` | :Canonical name: `numpy.byte` | :Alias on this platform (win32 AMD64): `numpy.int8`: 8-bit signed integer (``-128`` to ``127``). | | Method resolution order: | int8 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | int8.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.int8(127).bit_count() | 7 | >>> np.int8(-127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.bytes_
Python Library Documentation: class bytes_ in module numpy
class bytes_(builtins.bytes, character)
| A byte string.
|
| When used in arrays, this type strips trailing null bytes.
|
| :Character code: ``'S'``
|
| Method resolution order:
| bytes_
| builtins.bytes
| character
| flexible
| generic
| builtins.object
|
| Methods defined here:
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __str__(self, /)
| Return str(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.bytes:
|
| __add__(self, value, /)
| Return self+value.
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __bytes__(self, /)
| Convert this value to exact type bytes.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __iter__(self, /)
| Implement iter(self).
|
| __len__(self, /)
| Return len(self).
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| capitalize(...)
| B.capitalize() -> copy of B
|
| Return a copy of B with only its first character capitalized (ASCII)
| and the rest lower-cased.
|
| center(self, width, fillchar=b' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character.
|
| count(...)
| B.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of subsection sub in
| bytes B[start:end]. Optional arguments start and end are interpreted
| as in slice notation.
|
| decode(self, /, encoding='utf-8', errors='strict')
| Decode the bytes using the codec registered for encoding.
|
| encoding
| The encoding with which to decode the bytes.
| errors
| The error handling scheme to use for the handling of decoding errors.
| The default is 'strict' meaning that decoding errors raise a
| UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
| as well as any other name registered with codecs.register_error that
| can handle UnicodeDecodeErrors.
|
| endswith(...)
| B.endswith(suffix[, start[, end]]) -> bool
|
| Return True if B ends with the specified suffix, False otherwise.
| With optional start, test B beginning at that position.
| With optional end, stop comparing B at that position.
| suffix can also be a tuple of bytes to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| B.find(sub[, start[, end]]) -> int
|
| Return the lowest index in B where subsection sub is found,
| such that sub is contained within B[start,end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| hex(...)
| Create a string of hexadecimal numbers from a bytes object.
|
| sep
| An optional single character or byte to separate hex bytes.
| bytes_per_sep
| How many bytes between separators. Positive values count from the
| right, negative values count from the left.
|
| Example:
| >>> value = b'\xb9\x01\xef'
| >>> value.hex()
| 'b901ef'
| >>> value.hex(':')
| 'b9:01:ef'
| >>> value.hex(':', 2)
| 'b9:01ef'
| >>> value.hex(':', -2)
| 'b901:ef'
|
| index(...)
| B.index(sub[, start[, end]]) -> int
|
| Return the lowest index in B where subsection sub is found,
| such that sub is contained within B[start,end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the subsection is not found.
|
| isalnum(...)
| B.isalnum() -> bool
|
| Return True if all characters in B are alphanumeric
| and there is at least one character in B, False otherwise.
|
| isalpha(...)
| B.isalpha() -> bool
|
| Return True if all characters in B are alphabetic
| and there is at least one character in B, False otherwise.
|
| isascii(...)
| B.isascii() -> bool
|
| Return True if B is empty or all characters in B are ASCII,
| False otherwise.
|
| isdigit(...)
| B.isdigit() -> bool
|
| Return True if all characters in B are digits
| and there is at least one character in B, False otherwise.
|
| islower(...)
| B.islower() -> bool
|
| Return True if all cased characters in B are lowercase and there is
| at least one cased character in B, False otherwise.
|
| isspace(...)
| B.isspace() -> bool
|
| Return True if all characters in B are whitespace
| and there is at least one character in B, False otherwise.
|
| istitle(...)
| B.istitle() -> bool
|
| Return True if B is a titlecased string and there is at least one
| character in B, i.e. uppercase characters may only follow uncased
| characters and lowercase characters only cased ones. Return False
| otherwise.
|
| isupper(...)
| B.isupper() -> bool
|
| Return True if all cased characters in B are uppercase and there is
| at least one cased character in B, False otherwise.
|
| join(self, iterable_of_bytes, /)
| Concatenate any number of bytes objects.
|
| The bytes whose method is called is inserted in between each pair.
|
| The result is returned as a new bytes object.
|
| Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.
|
| ljust(self, width, fillchar=b' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character.
|
| lower(...)
| B.lower() -> copy of B
|
| Return a copy of B with all ASCII characters converted to lowercase.
|
| lstrip(self, bytes=None, /)
| Strip leading bytes contained in the argument.
|
| If the argument is omitted or None, strip leading ASCII whitespace.
|
| partition(self, sep, /)
| Partition the bytes into three parts using the given separator.
|
| This will search for the separator sep in the bytes. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original bytes
| object and two empty bytes objects.
|
| removeprefix(self, prefix, /)
| Return a bytes object with the given prefix string removed if present.
|
| If the bytes starts with the prefix string, return bytes[len(prefix):].
| Otherwise, return a copy of the original bytes.
|
| removesuffix(self, suffix, /)
| Return a bytes object with the given suffix string removed if present.
|
| If the bytes ends with the suffix string and that suffix is not empty,
| return bytes[:-len(prefix)]. Otherwise, return a copy of the original
| bytes.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| B.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in B where subsection sub is found,
| such that sub is contained within B[start,end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| B.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in B where subsection sub is found,
| such that sub is contained within B[start,end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raise ValueError when the subsection is not found.
|
| rjust(self, width, fillchar=b' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character.
|
| rpartition(self, sep, /)
| Partition the bytes into three parts using the given separator.
|
| This will search for the separator sep in the bytes, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty bytes
| objects and the original bytes object.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the sections in the bytes, using sep as the delimiter.
|
| sep
| The delimiter according which to split the bytes.
| None (the default value) means split on ASCII whitespace characters
| (space, tab, return, newline, formfeed, vertical tab).
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
|
| Splitting is done starting at the end of the bytes and working to the front.
|
| rstrip(self, bytes=None, /)
| Strip trailing bytes contained in the argument.
|
| If the argument is omitted or None, strip trailing ASCII whitespace.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the sections in the bytes, using sep as the delimiter.
|
| sep
| The delimiter according which to split the bytes.
| None (the default value) means split on ASCII whitespace characters
| (space, tab, return, newline, formfeed, vertical tab).
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the bytes, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| B.startswith(prefix[, start[, end]]) -> bool
|
| Return True if B starts with the specified prefix, False otherwise.
| With optional start, test B beginning at that position.
| With optional end, stop comparing B at that position.
| prefix can also be a tuple of bytes to try.
|
| strip(self, bytes=None, /)
| Strip leading and trailing bytes contained in the argument.
|
| If the argument is omitted or None, strip leading and trailing ASCII whitespace.
|
| swapcase(...)
| B.swapcase() -> copy of B
|
| Return a copy of B with uppercase ASCII characters converted
| to lowercase ASCII and vice versa.
|
| title(...)
| B.title() -> copy of B
|
| Return a titlecased version of B, i.e. ASCII words start with uppercase
| characters, all remaining cased characters have lowercase.
|
| translate(self, table, /, delete=b'')
| Return a copy with each character mapped by the given translation table.
|
| table
| Translation table, which must be a bytes object of length 256.
|
| All characters occurring in the optional argument delete are removed.
| The remaining characters are mapped through the given translation table.
|
| upper(...)
| B.upper() -> copy of B
|
| Return a copy of B with all ASCII characters converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The original string is never truncated.
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.bytes:
|
| fromhex(string, /)
| Create a bytes object from a string of hexadecimal numbers.
|
| Spaces between two numbers are accepted.
| Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.bytes:
|
| maketrans(frm, to, /)
| Return a translation table useable for the bytes or bytearray translate method.
|
| The returned table will be one where each byte in frm is mapped to the byte at
| the same position in to.
|
| The bytes objects frm and to must be of the same length.
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __abs__(self, /)
| abs(self)
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __bool__(self, /)
| True if self else False
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| NumPy array scalar formatter
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| Helper for pickle.
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setstate__(...)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| base
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.base`.
|
| data
| Pointer to start of data.
|
| device
|
| dtype
| Get array data-descriptor.
|
| flags
| The integer value of flags.
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
numpy.c_
Python Library Documentation: CClass in module numpy.lib._index_tricks_impl object
class CClass(AxisConcatenator)
| Translates slice objects to concatenation along the second axis.
|
| This is short-hand for ``np.r_['-1,2,0', index expression]``, which is
| useful because of its common occurrence. In particular, arrays will be
| stacked along their last axis after being upgraded to at least 2-D with
| 1's post-pended to the shape (column vectors made out of 1-D arrays).
|
| See Also
| --------
| column_stack : Stack 1-D arrays as columns into a 2-D array.
| r_ : For more detailed documentation.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.c_[np.array([1,2,3]), np.array([4,5,6])]
| array([[1, 4],
| [2, 5],
| [3, 6]])
| >>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]
| array([[1, 2, 3, ..., 4, 5, 6]])
|
| Method resolution order:
| CClass
| AxisConcatenator
| builtins.object
|
| Methods defined here:
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from AxisConcatenator:
|
| __getitem__(self, key)
|
| __len__(self)
|
| ----------------------------------------------------------------------
| Static methods inherited from AxisConcatenator:
|
| concatenate(...)
| concatenate(
| (a1, a2, ...),
| axis=0,
| out=None,
| dtype=None,
| casting="same_kind"
| )
|
| Join a sequence of arrays along an existing axis.
|
| Parameters
| ----------
| a1, a2, ... : sequence of array_like
| The arrays must have the same shape, except in the dimension
| corresponding to `axis` (the first, by default).
| axis : int, optional
| The axis along which the arrays will be joined. If axis is None,
| arrays are flattened before use. Default is 0.
| out : ndarray, optional
| If provided, the destination to place the result. The shape must be
| correct, matching that of what concatenate would have returned if no
| out argument were specified.
| dtype : str or dtype
| If provided, the destination array will have this dtype. Cannot be
| provided together with `out`.
|
| .. versionadded:: 1.20.0
|
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'same_kind'.
| For a description of the options, please see :term:`casting`.
|
| .. versionadded:: 1.20.0
|
| Returns
| -------
| res : ndarray
| The concatenated array.
|
| See Also
| --------
| ma.concatenate : Concatenate function that preserves input masks.
| array_split : Split an array into multiple sub-arrays of equal or
| near-equal size.
| split : Split array into a list of multiple sub-arrays of equal size.
| hsplit : Split array into multiple sub-arrays horizontally (column wise).
| vsplit : Split array into multiple sub-arrays vertically (row wise).
| dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
| stack : Stack a sequence of arrays along a new axis.
| block : Assemble arrays from blocks.
| hstack : Stack arrays in sequence horizontally (column wise).
| vstack : Stack arrays in sequence vertically (row wise).
| dstack : Stack arrays in sequence depth wise (along third dimension).
| column_stack : Stack 1-D arrays as columns into a 2-D array.
|
| Notes
| -----
| When one or more of the arrays to be concatenated is a MaskedArray,
| this function will return a MaskedArray object instead of an ndarray,
| but the input masks are *not* preserved. In cases where a MaskedArray
| is expected as input, use the ma.concatenate function from the masked
| array module instead.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> b = np.array([[5, 6]])
| >>> np.concatenate((a, b), axis=0)
| array([[1, 2],
| [3, 4],
| [5, 6]])
| >>> np.concatenate((a, b.T), axis=1)
| array([[1, 2, 5],
| [3, 4, 6]])
| >>> np.concatenate((a, b), axis=None)
| array([1, 2, 3, 4, 5, 6])
|
| This function will not preserve masking of MaskedArray inputs.
|
| >>> a = np.ma.arange(3)
| >>> a[1] = np.ma.masked
| >>> b = np.arange(2, 5)
| >>> a
| masked_array(data=[0, --, 2],
| mask=[False, True, False],
| fill_value=999999)
| >>> b
| array([2, 3, 4])
| >>> np.concatenate([a, b])
| masked_array(data=[0, 1, 2, 2, 3, 4],
| mask=False,
| fill_value=999999)
| >>> np.ma.concatenate([a, b])
| masked_array(data=[0, --, 2, 2, 3, 4],
| mask=[False, True, False, False, False, False],
| fill_value=999999)
|
| makemat = class matrix(ndarray)
| | makemat(data, dtype=None, copy=True)
| |
| | matrix(data, dtype=None, copy=True)
| |
| | Returns a matrix from an array-like object, or from a string of data.
| |
| | A matrix is a specialized 2-D array that retains its 2-D nature
| | through operations. It has certain special operators, such as ``*``
| | (matrix multiplication) and ``**`` (matrix power).
| |
| | .. note:: It is no longer recommended to use this class, even for linear
| | algebra. Instead use regular arrays. The class may be removed
| | in the future.
| |
| | Parameters
| | ----------
| | data : array_like or string
| | If `data` is a string, it is interpreted as a matrix with commas
| | or spaces separating columns, and semicolons separating rows.
| | dtype : data-type
| | Data-type of the output matrix.
| | copy : bool
| | If `data` is already an `ndarray`, then this flag determines
| | whether the data is copied (the default), or whether a view is
| | constructed.
| |
| | See Also
| | --------
| | array
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.matrix('1 2; 3 4')
| | >>> a
| | matrix([[1, 2],
| | [3, 4]])
| |
| | >>> np.matrix([[1, 2], [3, 4]])
| | matrix([[1, 2],
| | [3, 4]])
| |
| | Method resolution order:
| | matrix
| | ndarray
| | builtins.object
| |
| | Methods defined here:
| |
| | __array_finalize__(self, obj) from numpy.matrixlib.defmatrix.matrix
| | a.__array_finalize__(obj, /)
| |
| | Present so subclasses can call super. Does nothing.
| |
| | __getitem__(self, index) from numpy.matrixlib.defmatrix.matrix
| | Return self[key].
| |
| | __imul__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return self*=value.
| |
| | __ipow__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return self**=value.
| |
| | __mul__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return self*value.
| |
| | __pow__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return pow(self, value, mod).
| |
| | __rmul__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return value*self.
| |
| | __rpow__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return pow(value, self, mod).
| |
| | all(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Test whether all matrix elements along a given axis evaluate to True.
| |
| | Parameters
| | ----------
| | See `numpy.all` for complete descriptions
| |
| | See Also
| | --------
| | numpy.all
| |
| | Notes
| | -----
| | This is the same as `ndarray.all`, but it returns a `matrix` object.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> y = x[0]; y
| | matrix([[0, 1, 2, 3]])
| | >>> (x == y)
| | matrix([[ True, True, True, True],
| | [False, False, False, False],
| | [False, False, False, False]])
| | >>> (x == y).all()
| | False
| | >>> (x == y).all(0)
| | matrix([[False, False, False, False]])
| | >>> (x == y).all(1)
| | matrix([[ True],
| | [False],
| | [False]])
| |
| | any(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Test whether any array element along a given axis evaluates to True.
| |
| | Refer to `numpy.any` for full documentation.
| |
| | Parameters
| | ----------
| | axis : int, optional
| | Axis along which logical OR is performed
| | out : ndarray, optional
| | Output to existing array instead of creating new one, must have
| | same shape as expected output
| |
| | Returns
| | -------
| | any : bool, ndarray
| | Returns a single bool if `axis` is ``None``; otherwise,
| | returns `ndarray`
| |
| | argmax(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Indexes of the maximum values along an axis.
| |
| | Return the indexes of the first occurrences of the maximum values
| | along the specified axis. If axis is None, the index is for the
| | flattened matrix.
| |
| | Parameters
| | ----------
| | See `numpy.argmax` for complete descriptions
| |
| | See Also
| | --------
| | numpy.argmax
| |
| | Notes
| | -----
| | This is the same as `ndarray.argmax`, but returns a `matrix` object
| | where `ndarray.argmax` would return an `ndarray`.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.argmax()
| | 11
| | >>> x.argmax(0)
| | matrix([[2, 2, 2, 2]])
| | >>> x.argmax(1)
| | matrix([[3],
| | [3],
| | [3]])
| |
| | argmin(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Indexes of the minimum values along an axis.
| |
| | Return the indexes of the first occurrences of the minimum values
| | along the specified axis. If axis is None, the index is for the
| | flattened matrix.
| |
| | Parameters
| | ----------
| | See `numpy.argmin` for complete descriptions.
| |
| | See Also
| | --------
| | numpy.argmin
| |
| | Notes
| | -----
| | This is the same as `ndarray.argmin`, but returns a `matrix` object
| | where `ndarray.argmin` would return an `ndarray`.
| |
| | Examples
| | --------
| | >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, -1, -2, -3],
| | [ -4, -5, -6, -7],
| | [ -8, -9, -10, -11]])
| | >>> x.argmin()
| | 11
| | >>> x.argmin(0)
| | matrix([[2, 2, 2, 2]])
| | >>> x.argmin(1)
| | matrix([[3],
| | [3],
| | [3]])
| |
| | flatten(self, order='C') from numpy.matrixlib.defmatrix.matrix
| | Return a flattened copy of the matrix.
| |
| | All `N` elements of the matrix are placed into a single row.
| |
| | Parameters
| | ----------
| | order : {'C', 'F', 'A', 'K'}, optional
| | 'C' means to flatten in row-major (C-style) order. 'F' means to
| | flatten in column-major (Fortran-style) order. 'A' means to
| | flatten in column-major order if `m` is Fortran *contiguous* in
| | memory, row-major order otherwise. 'K' means to flatten `m` in
| | the order the elements occur in memory. The default is 'C'.
| |
| | Returns
| | -------
| | y : matrix
| | A copy of the matrix, flattened to a `(1, N)` matrix where `N`
| | is the number of elements in the original matrix.
| |
| | See Also
| | --------
| | ravel : Return a flattened array.
| | flat : A 1-D flat iterator over the matrix.
| |
| | Examples
| | --------
| | >>> m = np.matrix([[1,2], [3,4]])
| | >>> m.flatten()
| | matrix([[1, 2, 3, 4]])
| | >>> m.flatten('F')
| | matrix([[1, 3, 2, 4]])
| |
| | getA = A(self) from numpy.matrixlib.defmatrix.matrix
| | Return `self` as an `ndarray` object.
| |
| | Equivalent to ``np.asarray(self)``.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : ndarray
| | `self` as an `ndarray`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.getA()
| | array([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| |
| | getA1 = A1(self) from numpy.matrixlib.defmatrix.matrix
| | Return `self` as a flattened `ndarray`.
| |
| | Equivalent to ``np.asarray(x).ravel()``
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : ndarray
| | `self`, 1-D, as an `ndarray`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.getA1()
| | array([ 0, 1, 2, ..., 9, 10, 11])
| |
| | getH = H(self) from numpy.matrixlib.defmatrix.matrix
| | Returns the (complex) conjugate transpose of `self`.
| |
| | Equivalent to ``np.transpose(self)`` if `self` is real-valued.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | complex conjugate transpose of `self`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4)))
| | >>> z = x - 1j*x; z
| | matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
| | [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
| | [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
| | >>> z.getH()
| | matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
| | [ 1. +1.j, 5. +5.j, 9. +9.j],
| | [ 2. +2.j, 6. +6.j, 10.+10.j],
| | [ 3. +3.j, 7. +7.j, 11.+11.j]])
| |
| | getI = I(self) from numpy.matrixlib.defmatrix.matrix
| | Returns the (multiplicative) inverse of invertible `self`.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | If `self` is non-singular, `ret` is such that ``ret * self`` ==
| | ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
| | ``True``.
| |
| | Raises
| | ------
| | numpy.linalg.LinAlgError: Singular matrix
| | If `self` is singular.
| |
| | See Also
| | --------
| | linalg.inv
| |
| | Examples
| | --------
| | >>> m = np.matrix('[1, 2; 3, 4]'); m
| | matrix([[1, 2],
| | [3, 4]])
| | >>> m.getI()
| | matrix([[-2. , 1. ],
| | [ 1.5, -0.5]])
| | >>> m.getI() * m
| | matrix([[ 1., 0.], # may vary
| | [ 0., 1.]])
| |
| | getT = T(self) from numpy.matrixlib.defmatrix.matrix
| | Returns the transpose of the matrix.
| |
| | Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | The (non-conjugated) transpose of the matrix.
| |
| | See Also
| | --------
| | transpose, getH
| |
| | Examples
| | --------
| | >>> m = np.matrix('[1, 2; 3, 4]')
| | >>> m
| | matrix([[1, 2],
| | [3, 4]])
| | >>> m.getT()
| | matrix([[1, 3],
| | [2, 4]])
| |
| | max(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Return the maximum value along an axis.
| |
| | Parameters
| | ----------
| | See `amax` for complete descriptions
| |
| | See Also
| | --------
| | amax, ndarray.max
| |
| | Notes
| | -----
| | This is the same as `ndarray.max`, but returns a `matrix` object
| | where `ndarray.max` would return an ndarray.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.max()
| | 11
| | >>> x.max(0)
| | matrix([[ 8, 9, 10, 11]])
| | >>> x.max(1)
| | matrix([[ 3],
| | [ 7],
| | [11]])
| |
| | mean(self, axis=None, dtype=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Returns the average of the matrix elements along the given axis.
| |
| | Refer to `numpy.mean` for full documentation.
| |
| | See Also
| | --------
| | numpy.mean
| |
| | Notes
| | -----
| | Same as `ndarray.mean` except that, where that returns an `ndarray`,
| | this returns a `matrix` object.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3, 4)))
| | >>> x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.mean()
| | 5.5
| | >>> x.mean(0)
| | matrix([[4., 5., 6., 7.]])
| | >>> x.mean(1)
| | matrix([[ 1.5],
| | [ 5.5],
| | [ 9.5]])
| |
| | min(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Return the minimum value along an axis.
| |
| | Parameters
| | ----------
| | See `amin` for complete descriptions.
| |
| | See Also
| | --------
| | amin, ndarray.min
| |
| | Notes
| | -----
| | This is the same as `ndarray.min`, but returns a `matrix` object
| | where `ndarray.min` would return an ndarray.
| |
| | Examples
| | --------
| | >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, -1, -2, -3],
| | [ -4, -5, -6, -7],
| | [ -8, -9, -10, -11]])
| | >>> x.min()
| | -11
| | >>> x.min(0)
| | matrix([[ -8, -9, -10, -11]])
| | >>> x.min(1)
| | matrix([[ -3],
| | [ -7],
| | [-11]])
| |
| | prod(self, axis=None, dtype=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Return the product of the array elements over the given axis.
| |
| | Refer to `prod` for full documentation.
| |
| | See Also
| | --------
| | prod, ndarray.prod
| |
| | Notes
| | -----
| | Same as `ndarray.prod`, except, where that returns an `ndarray`, this
| | returns a `matrix` object instead.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.prod()
| | 0
| | >>> x.prod(0)
| | matrix([[ 0, 45, 120, 231]])
| | >>> x.prod(1)
| | matrix([[ 0],
| | [ 840],
| | [7920]])
| |
| | ptp(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Peak-to-peak (maximum - minimum) value along the given axis.
| |
| | Refer to `numpy.ptp` for full documentation.
| |
| | See Also
| | --------
| | numpy.ptp
| |
| | Notes
| | -----
| | Same as `ndarray.ptp`, except, where that would return an `ndarray` object,
| | this returns a `matrix` object.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.ptp()
| | 11
| | >>> x.ptp(0)
| | matrix([[8, 8, 8, 8]])
| | >>> x.ptp(1)
| | matrix([[3],
| | [3],
| | [3]])
| |
| | ravel(self, order='C') from numpy.matrixlib.defmatrix.matrix
| | Return a flattened matrix.
| |
| | Refer to `numpy.ravel` for more documentation.
| |
| | Parameters
| | ----------
| | order : {'C', 'F', 'A', 'K'}, optional
| | The elements of `m` are read using this index order. 'C' means to
| | index the elements in C-like order, with the last axis index
| | changing fastest, back to the first axis index changing slowest.
| | 'F' means to index the elements in Fortran-like index order, with
| | the first index changing fastest, and the last index changing
| | slowest. Note that the 'C' and 'F' options take no account of the
| | memory layout of the underlying array, and only refer to the order
| | of axis indexing. 'A' means to read the elements in Fortran-like
| | index order if `m` is Fortran *contiguous* in memory, C-like order
| | otherwise. 'K' means to read the elements in the order they occur
| | in memory, except for reversing the data when strides are negative.
| | By default, 'C' index order is used.
| |
| | Returns
| | -------
| | ret : matrix
| | Return the matrix flattened to shape `(1, N)` where `N`
| | is the number of elements in the original matrix.
| | A copy is made only if necessary.
| |
| | See Also
| | --------
| | matrix.flatten : returns a similar output matrix but always a copy
| | matrix.flat : a flat iterator on the array.
| | numpy.ravel : related function which returns an ndarray
| |
| | squeeze(self, axis=None) from numpy.matrixlib.defmatrix.matrix
| | Return a possibly reshaped matrix.
| |
| | Refer to `numpy.squeeze` for more documentation.
| |
| | Parameters
| | ----------
| | axis : None or int or tuple of ints, optional
| | Selects a subset of the axes of length one in the shape.
| | If an axis is selected with shape entry greater than one,
| | an error is raised.
| |
| | Returns
| | -------
| | squeezed : matrix
| | The matrix, but as a (1, N) matrix if it had shape (N, 1).
| |
| | See Also
| | --------
| | numpy.squeeze : related function
| |
| | Notes
| | -----
| | If `m` has a single column then that column is returned
| | as the single row of a matrix. Otherwise `m` is returned.
| | The returned matrix is always either `m` itself or a view into `m`.
| | Supplying an axis keyword argument will not affect the returned matrix
| | but it may cause an error to be raised.
| |
| | Examples
| | --------
| | >>> c = np.matrix([[1], [2]])
| | >>> c
| | matrix([[1],
| | [2]])
| | >>> c.squeeze()
| | matrix([[1, 2]])
| | >>> r = c.T
| | >>> r
| | matrix([[1, 2]])
| | >>> r.squeeze()
| | matrix([[1, 2]])
| | >>> m = np.matrix([[1, 2], [3, 4]])
| | >>> m.squeeze()
| | matrix([[1, 2],
| | [3, 4]])
| |
| | std(self, axis=None, dtype=None, out=None, ddof=0) from numpy.matrixlib.defmatrix.matrix
| | Return the standard deviation of the array elements along the given axis.
| |
| | Refer to `numpy.std` for full documentation.
| |
| | See Also
| | --------
| | numpy.std
| |
| | Notes
| | -----
| | This is the same as `ndarray.std`, except that where an `ndarray` would
| | be returned, a `matrix` object is returned instead.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3, 4)))
| | >>> x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.std()
| | 3.4520525295346629 # may vary
| | >>> x.std(0)
| | matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary
| | >>> x.std(1)
| | matrix([[ 1.11803399],
| | [ 1.11803399],
| | [ 1.11803399]])
| |
| | sum(self, axis=None, dtype=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Returns the sum of the matrix elements, along the given axis.
| |
| | Refer to `numpy.sum` for full documentation.
| |
| | See Also
| | --------
| | numpy.sum
| |
| | Notes
| | -----
| | This is the same as `ndarray.sum`, except that where an `ndarray` would
| | be returned, a `matrix` object is returned instead.
| |
| | Examples
| | --------
| | >>> x = np.matrix([[1, 2], [4, 3]])
| | >>> x.sum()
| | 10
| | >>> x.sum(axis=1)
| | matrix([[3],
| | [7]])
| | >>> x.sum(axis=1, dtype='float')
| | matrix([[3.],
| | [7.]])
| | >>> out = np.zeros((2, 1), dtype='float')
| | >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out))
| | matrix([[3.],
| | [7.]])
| |
| | tolist(self) from numpy.matrixlib.defmatrix.matrix
| | Return the matrix as a (possibly nested) list.
| |
| | See `ndarray.tolist` for full documentation.
| |
| | See Also
| | --------
| | ndarray.tolist
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.tolist()
| | [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
| |
| | var(self, axis=None, dtype=None, out=None, ddof=0) from numpy.matrixlib.defmatrix.matrix
| | Returns the variance of the matrix elements, along the given axis.
| |
| | Refer to `numpy.var` for full documentation.
| |
| | See Also
| | --------
| | numpy.var
| |
| | Notes
| | -----
| | This is the same as `ndarray.var`, except that where an `ndarray` would
| | be returned, a `matrix` object is returned instead.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3, 4)))
| | >>> x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.var()
| | 11.916666666666666
| | >>> x.var(0)
| | matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary
| | >>> x.var(1)
| | matrix([[1.25],
| | [1.25],
| | [1.25]])
| |
| | ----------------------------------------------------------------------
| | Static methods defined here:
| |
| | __new__(subtype, data, dtype=None, copy=True) from numpy.matrixlib.defmatrix.matrix
| | Create and return a new object. See help(type) for accurate signature.
| |
| | ----------------------------------------------------------------------
| | Readonly properties defined here:
| |
| | A
| | Return `self` as an `ndarray` object.
| |
| | Equivalent to ``np.asarray(self)``.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : ndarray
| | `self` as an `ndarray`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.getA()
| | array([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| |
| | A1
| | Return `self` as a flattened `ndarray`.
| |
| | Equivalent to ``np.asarray(x).ravel()``
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : ndarray
| | `self`, 1-D, as an `ndarray`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.getA1()
| | array([ 0, 1, 2, ..., 9, 10, 11])
| |
| | H
| | Returns the (complex) conjugate transpose of `self`.
| |
| | Equivalent to ``np.transpose(self)`` if `self` is real-valued.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | complex conjugate transpose of `self`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4)))
| | >>> z = x - 1j*x; z
| | matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
| | [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
| | [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
| | >>> z.getH()
| | matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
| | [ 1. +1.j, 5. +5.j, 9. +9.j],
| | [ 2. +2.j, 6. +6.j, 10.+10.j],
| | [ 3. +3.j, 7. +7.j, 11.+11.j]])
| |
| | I
| | Returns the (multiplicative) inverse of invertible `self`.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | If `self` is non-singular, `ret` is such that ``ret * self`` ==
| | ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
| | ``True``.
| |
| | Raises
| | ------
| | numpy.linalg.LinAlgError: Singular matrix
| | If `self` is singular.
| |
| | See Also
| | --------
| | linalg.inv
| |
| | Examples
| | --------
| | >>> m = np.matrix('[1, 2; 3, 4]'); m
| | matrix([[1, 2],
| | [3, 4]])
| | >>> m.getI()
| | matrix([[-2. , 1. ],
| | [ 1.5, -0.5]])
| | >>> m.getI() * m
| | matrix([[ 1., 0.], # may vary
| | [ 0., 1.]])
| |
| | T
| | Returns the transpose of the matrix.
| |
| | Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | The (non-conjugated) transpose of the matrix.
| |
| | See Also
| | --------
| | transpose, getH
| |
| | Examples
| | --------
| | >>> m = np.matrix('[1, 2; 3, 4]')
| | >>> m
| | matrix([[1, 2],
| | [3, 4]])
| | >>> m.getT()
| | matrix([[1, 3],
| | [2, 4]])
| |
| | ----------------------------------------------------------------------
| | Data descriptors defined here:
| |
| | __dict__
| | dictionary for instance variables
| |
| | ----------------------------------------------------------------------
| | Data and other attributes defined here:
| |
| | __annotations__ = {}
| |
| | __array_priority__ = 10.0
| |
| | ----------------------------------------------------------------------
| | Methods inherited from ndarray:
| |
| | __abs__(self, /)
| | abs(self)
| |
| | __add__(self, value, /)
| | Return self+value.
| |
| | __and__(self, value, /)
| | Return self&value.
| |
| | __array__(...)
| | a.__array__([dtype], *, copy=None)
| |
| | For ``dtype`` parameter it returns a new reference to self if
| | ``dtype`` is not given or it matches array's data type.
| | A new array of provided data type is returned if ``dtype``
| | is different from the current data type of the array.
| | For ``copy`` parameter it returns a new reference to self if
| | ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| | parameter. The method returns a new array for ``copy=True``, regardless of
| | ``dtype`` parameter.
| |
| | A more detailed explanation of the ``__array__`` interface
| | can be found in :ref:`dunder_array.interface`.
| |
| | __array_function__(...)
| |
| | __array_namespace__(...)
| |
| | __array_ufunc__(...)
| |
| | __array_wrap__(...)
| | a.__array_wrap__(array[, context], /)
| |
| | Returns a view of `array` with the same type as self.
| |
| | __bool__(self, /)
| | True if self else False
| |
| | __buffer__(self, flags, /)
| | Return a buffer object that exposes the underlying memory of the object.
| |
| | __complex__(...)
| |
| | __contains__(self, key, /)
| | Return bool(key in self).
| |
| | __copy__(...)
| | a.__copy__()
| |
| | Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
| |
| | Equivalent to ``a.copy(order='K')``.
| |
| | __deepcopy__(...)
| | a.__deepcopy__(memo, /)
| |
| | Used if :func:`copy.deepcopy` is called on an array.
| |
| | __delitem__(self, key, /)
| | Delete self[key].
| |
| | __divmod__(self, value, /)
| | Return divmod(self, value).
| |
| | __dlpack__(...)
| | a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
| |
| | DLPack Protocol: Part of the Array API.
| |
| | __dlpack_device__(...)
| | a.__dlpack_device__()
| |
| | DLPack Protocol: Part of the Array API.
| |
| | __eq__(self, value, /)
| | Return self==value.
| |
| | __float__(self, /)
| | float(self)
| |
| | __floordiv__(self, value, /)
| | Return self//value.
| |
| | __format__(...)
| | Default object formatter.
| |
| | Return str(self) if format_spec is empty. Raise TypeError otherwise.
| |
| | __ge__(self, value, /)
| | Return self>=value.
| |
| | __gt__(self, value, /)
| | Return self>value.
| |
| | __iadd__(self, value, /)
| | Return self+=value.
| |
| | __iand__(self, value, /)
| | Return self&=value.
| |
| | __ifloordiv__(self, value, /)
| | Return self//=value.
| |
| | __ilshift__(self, value, /)
| | Return self<<=value.
| |
| | __imatmul__(self, value, /)
| | Return self@=value.
| |
| | __imod__(self, value, /)
| | Return self%=value.
| |
| | __index__(self, /)
| | Return self converted to an integer, if self is suitable for use as an index into a list.
| |
| | __int__(self, /)
| | int(self)
| |
| | __invert__(self, /)
| | ~self
| |
| | __ior__(self, value, /)
| | Return self|=value.
| |
| | __irshift__(self, value, /)
| | Return self>>=value.
| |
| | __isub__(self, value, /)
| | Return self-=value.
| |
| | __iter__(self, /)
| | Implement iter(self).
| |
| | __itruediv__(self, value, /)
| | Return self/=value.
| |
| | __ixor__(self, value, /)
| | Return self^=value.
| |
| | __le__(self, value, /)
| | Return self<=value.
| |
| | __len__(self, /)
| | Return len(self).
| |
| | __lshift__(self, value, /)
| | Return self<<value.
| |
| | __lt__(self, value, /)
| | Return self<value.
| |
| | __matmul__(self, value, /)
| | Return self@value.
| |
| | __mod__(self, value, /)
| | Return self%value.
| |
| | __ne__(self, value, /)
| | Return self!=value.
| |
| | __neg__(self, /)
| | -self
| |
| | __or__(self, value, /)
| | Return self|value.
| |
| | __pos__(self, /)
| | +self
| |
| | __radd__(self, value, /)
| | Return value+self.
| |
| | __rand__(self, value, /)
| | Return value&self.
| |
| | __rdivmod__(self, value, /)
| | Return divmod(value, self).
| |
| | __reduce__(...)
| | a.__reduce__()
| |
| | For pickling.
| |
| | __reduce_ex__(...)
| | Helper for pickle.
| |
| | __repr__(self, /)
| | Return repr(self).
| |
| | __rfloordiv__(self, value, /)
| | Return value//self.
| |
| | __rlshift__(self, value, /)
| | Return value<<self.
| |
| | __rmatmul__(self, value, /)
| | Return value@self.
| |
| | __rmod__(self, value, /)
| | Return value%self.
| |
| | __ror__(self, value, /)
| | Return value|self.
| |
| | __rrshift__(self, value, /)
| | Return value>>self.
| |
| | __rshift__(self, value, /)
| | Return self>>value.
| |
| | __rsub__(self, value, /)
| | Return value-self.
| |
| | __rtruediv__(self, value, /)
| | Return value/self.
| |
| | __rxor__(self, value, /)
| | Return value^self.
| |
| | __setitem__(self, key, value, /)
| | Set self[key] to value.
| |
| | __setstate__(...)
| | a.__setstate__(state, /)
| |
| | For unpickling.
| |
| | The `state` argument must be a sequence that contains the following
| | elements:
| |
| | Parameters
| | ----------
| | version : int
| | optional pickle version. If omitted defaults to 0.
| | shape : tuple
| | dtype : data-type
| | isFortran : bool
| | rawdata : string or list
| | a binary string with the data (or a list if 'a' is an object array)
| |
| | __sizeof__(...)
| | Size of object in memory, in bytes.
| |
| | __str__(self, /)
| | Return str(self).
| |
| | __sub__(self, value, /)
| | Return self-value.
| |
| | __truediv__(self, value, /)
| | Return self/value.
| |
| | __xor__(self, value, /)
| | Return self^value.
| |
| | argpartition(...)
| | a.argpartition(kth, axis=-1, kind='introselect', order=None)
| |
| | Returns the indices that would partition this array.
| |
| | Refer to `numpy.argpartition` for full documentation.
| |
| | .. versionadded:: 1.8.0
| |
| | See Also
| | --------
| | numpy.argpartition : equivalent function
| |
| | argsort(...)
| | a.argsort(axis=-1, kind=None, order=None)
| |
| | Returns the indices that would sort this array.
| |
| | Refer to `numpy.argsort` for full documentation.
| |
| | See Also
| | --------
| | numpy.argsort : equivalent function
| |
| | astype(...)
| | a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
| |
| | Copy of the array, cast to a specified type.
| |
| | Parameters
| | ----------
| | dtype : str or dtype
| | Typecode or data-type to which the array is cast.
| | order : {'C', 'F', 'A', 'K'}, optional
| | Controls the memory layout order of the result.
| | '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.
| | Default is 'K'.
| | casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| | Controls what kind of data casting may occur. Defaults to 'unsafe'
| | for backwards compatibility.
| |
| | * '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.
| | subok : bool, optional
| | If True, then sub-classes will be passed-through (default), otherwise
| | the returned array will be forced to be a base-class array.
| | copy : bool, optional
| | By default, astype always returns a newly allocated array. If this
| | is set to false, and the `dtype`, `order`, and `subok`
| | requirements are satisfied, the input array is returned instead
| | of a copy.
| |
| | Returns
| | -------
| | arr_t : ndarray
| | Unless `copy` is False and the other conditions for returning the input
| | array are satisfied (see description for `copy` input parameter), `arr_t`
| | is a new array of the same shape as the input array, with dtype, order
| | given by `dtype`, `order`.
| |
| | Notes
| | -----
| | .. versionchanged:: 1.17.0
| | Casting between a simple data type and a structured one is possible only
| | for "unsafe" casting. Casting to multiple fields is allowed, but
| | casting from multiple fields is not.
| |
| | .. versionchanged:: 1.9.0
| | Casting from numeric to string types in 'safe' casting mode requires
| | that the string dtype length is long enough to store the max
| | integer/float value converted.
| |
| | Raises
| | ------
| | ComplexWarning
| | When casting from complex to float or int. To avoid this,
| | one should use ``a.real.astype(t)``.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([1, 2, 2.5])
| | >>> x
| | array([1. , 2. , 2.5])
| |
| | >>> x.astype(int)
| | array([1, 2, 2])
| |
| | byteswap(...)
| | a.byteswap(inplace=False)
| |
| | Swap the bytes of the array elements
| |
| | Toggle between low-endian and big-endian data representation by
| | returning a byteswapped array, optionally swapped in-place.
| | Arrays of byte-strings are not swapped. The real and imaginary
| | parts of a complex number are swapped individually.
| |
| | Parameters
| | ----------
| | inplace : bool, optional
| | If ``True``, swap bytes in-place, default is ``False``.
| |
| | Returns
| | -------
| | out : ndarray
| | The byteswapped array. If `inplace` is ``True``, this is
| | a view to self.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> A = np.array([1, 256, 8755], dtype=np.int16)
| | >>> list(map(hex, A))
| | ['0x1', '0x100', '0x2233']
| | >>> A.byteswap(inplace=True)
| | array([ 256, 1, 13090], dtype=int16)
| | >>> list(map(hex, A))
| | ['0x100', '0x1', '0x3322']
| |
| | Arrays of byte-strings are not swapped
| |
| | >>> A = np.array([b'ceg', b'fac'])
| | >>> A.byteswap()
| | array([b'ceg', b'fac'], dtype='|S3')
| |
| | ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| | the same values but different representation in memory
| |
| | >>> A = np.array([1, 2, 3])
| | >>> A.view(np.uint8)
| | array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| | 0, 0], dtype=uint8)
| | >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| | array([1, 2, 3])
| | >>> A.view(np.uint8)
| | array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| | 0, 3], dtype=uint8)
| |
| | choose(...)
| | a.choose(choices, out=None, mode='raise')
| |
| | Use an index array to construct a new array from a set of choices.
| |
| | Refer to `numpy.choose` for full documentation.
| |
| | See Also
| | --------
| | numpy.choose : equivalent function
| |
| | clip(...)
| | a.clip(min=None, max=None, out=None, **kwargs)
| |
| | Return an array whose values are limited to ``[min, max]``.
| | One of max or min must be given.
| |
| | Refer to `numpy.clip` for full documentation.
| |
| | See Also
| | --------
| | numpy.clip : equivalent function
| |
| | compress(...)
| | a.compress(condition, axis=None, out=None)
| |
| | Return selected slices of this array along given axis.
| |
| | Refer to `numpy.compress` for full documentation.
| |
| | See Also
| | --------
| | numpy.compress : equivalent function
| |
| | conj(...)
| | a.conj()
| |
| | Complex-conjugate all elements.
| |
| | Refer to `numpy.conjugate` for full documentation.
| |
| | See Also
| | --------
| | numpy.conjugate : equivalent function
| |
| | conjugate(...)
| | a.conjugate()
| |
| | Return the complex conjugate, element-wise.
| |
| | Refer to `numpy.conjugate` for full documentation.
| |
| | See Also
| | --------
| | numpy.conjugate : equivalent function
| |
| | copy(...)
| | a.copy(order='C')
| |
| | Return a copy of the array.
| |
| | Parameters
| | ----------
| | order : {'C', 'F', 'A', 'K'}, optional
| | Controls the memory layout of the copy. 'C' means C-order,
| | 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| | 'C' otherwise. 'K' means match the layout of `a` as closely
| | as possible. (Note that this function and :func:`numpy.copy` are very
| | similar but have different default values for their order=
| | arguments, and this function always passes sub-classes through.)
| |
| | See also
| | --------
| | numpy.copy : Similar function with different default behavior
| | numpy.copyto
| |
| | Notes
| | -----
| | This function is the preferred method for creating an array copy. The
| | function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| | and will not pass sub-classes through by default.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([[1,2,3],[4,5,6]], order='F')
| |
| | >>> y = x.copy()
| |
| | >>> x.fill(0)
| |
| | >>> x
| | array([[0, 0, 0],
| | [0, 0, 0]])
| |
| | >>> y
| | array([[1, 2, 3],
| | [4, 5, 6]])
| |
| | >>> y.flags['C_CONTIGUOUS']
| | True
| |
| | For arrays containing Python objects (e.g. dtype=object),
| | the copy is a shallow one. The new array will contain the
| | same object which may lead to surprises if that object can
| | be modified (is mutable):
| |
| | >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| | >>> b = a.copy()
| | >>> b[2][0] = 10
| | >>> a
| | array([1, 'm', list([10, 3, 4])], dtype=object)
| |
| | To ensure all elements within an ``object`` array are copied,
| | use `copy.deepcopy`:
| |
| | >>> import copy
| | >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| | >>> c = copy.deepcopy(a)
| | >>> c[2][0] = 10
| | >>> c
| | array([1, 'm', list([10, 3, 4])], dtype=object)
| | >>> a
| | array([1, 'm', list([2, 3, 4])], dtype=object)
| |
| | cumprod(...)
| | a.cumprod(axis=None, dtype=None, out=None)
| |
| | Return the cumulative product of the elements along the given axis.
| |
| | Refer to `numpy.cumprod` for full documentation.
| |
| | See Also
| | --------
| | numpy.cumprod : equivalent function
| |
| | cumsum(...)
| | a.cumsum(axis=None, dtype=None, out=None)
| |
| | Return the cumulative sum of the elements along the given axis.
| |
| | Refer to `numpy.cumsum` for full documentation.
| |
| | See Also
| | --------
| | numpy.cumsum : equivalent function
| |
| | diagonal(...)
| | a.diagonal(offset=0, axis1=0, axis2=1)
| |
| | Return specified diagonals. In NumPy 1.9 the returned array is a
| | read-only view instead of a copy as in previous NumPy versions. In
| | a future version the read-only restriction will be removed.
| |
| | Refer to :func:`numpy.diagonal` for full documentation.
| |
| | See Also
| | --------
| | numpy.diagonal : equivalent function
| |
| | dot(...)
| |
| | dump(...)
| | a.dump(file)
| |
| | Dump a pickle of the array to the specified file.
| | The array can be read back with pickle.load or numpy.load.
| |
| | Parameters
| | ----------
| | file : str or Path
| | A string naming the dump file.
| |
| | .. versionchanged:: 1.17.0
| | `pathlib.Path` objects are now accepted.
| |
| | dumps(...)
| | a.dumps()
| |
| | Returns the pickle of the array as a string.
| | pickle.loads will convert the string back to an array.
| |
| | Parameters
| | ----------
| | None
| |
| | fill(...)
| | a.fill(value)
| |
| | Fill the array with a scalar value.
| |
| | Parameters
| | ----------
| | value : scalar
| | All elements of `a` will be assigned this value.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.array([1, 2])
| | >>> a.fill(0)
| | >>> a
| | array([0, 0])
| | >>> a = np.empty(2)
| | >>> a.fill(1)
| | >>> a
| | array([1., 1.])
| |
| | Fill expects a scalar value and always behaves the same as assigning
| | to a single array element. The following is a rare example where this
| | distinction is important:
| |
| | >>> a = np.array([None, None], dtype=object)
| | >>> a[0] = np.array(3)
| | >>> a
| | array([array(3), None], dtype=object)
| | >>> a.fill(np.array(3))
| | >>> a
| | array([array(3), array(3)], dtype=object)
| |
| | Where other forms of assignments will unpack the array being assigned:
| |
| | >>> a[...] = np.array(3)
| | >>> a
| | array([3, 3], dtype=object)
| |
| | getfield(...)
| | a.getfield(dtype, offset=0)
| |
| | Returns a field of the given array as a certain type.
| |
| | A field is a view of the array data with a given data-type. The values in
| | the view are determined by the given type and the offset into the current
| | array in bytes. The offset needs to be such that the view dtype fits in the
| | array dtype; for example an array of dtype complex128 has 16-byte elements.
| | If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| | between 0 and 12 bytes.
| |
| | Parameters
| | ----------
| | dtype : str or dtype
| | The data type of the view. The dtype size of the view can not be larger
| | than that of the array itself.
| | offset : int
| | Number of bytes to skip before beginning the element view.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.diag([1.+1.j]*2)
| | >>> x[1, 1] = 2 + 4.j
| | >>> x
| | array([[1.+1.j, 0.+0.j],
| | [0.+0.j, 2.+4.j]])
| | >>> x.getfield(np.float64)
| | array([[1., 0.],
| | [0., 2.]])
| |
| | By choosing an offset of 8 bytes we can select the complex part of the
| | array for our view:
| |
| | >>> x.getfield(np.float64, offset=8)
| | array([[1., 0.],
| | [0., 4.]])
| |
| | item(...)
| | a.item(*args)
| |
| | Copy an element of an array to a standard Python scalar and return it.
| |
| | Parameters
| | ----------
| | \*args : Arguments (variable number and type)
| |
| | * none: in this case, the method only works for arrays
| | with one element (`a.size == 1`), which element is
| | copied into a standard Python scalar object and returned.
| |
| | * int_type: this argument is interpreted as a flat index into
| | the array, specifying which element to copy and return.
| |
| | * tuple of int_types: functions as does a single int_type argument,
| | except that the argument is interpreted as an nd-index into the
| | array.
| |
| | Returns
| | -------
| | z : Standard Python scalar object
| | A copy of the specified element of the array as a suitable
| | Python scalar
| |
| | Notes
| | -----
| | When the data type of `a` is longdouble or clongdouble, item() returns
| | a scalar array object because there is no available Python scalar that
| | would not lose information. Void arrays return a buffer object for item(),
| | unless fields are defined, in which case a tuple is returned.
| |
| | `item` is very similar to a[args], except, instead of an array scalar,
| | a standard Python scalar is returned. This can be useful for speeding up
| | access to elements of the array and doing arithmetic on elements of the
| | array using Python's optimized math.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> np.random.seed(123)
| | >>> x = np.random.randint(9, size=(3, 3))
| | >>> x
| | array([[2, 2, 6],
| | [1, 3, 6],
| | [1, 0, 1]])
| | >>> x.item(3)
| | 1
| | >>> x.item(7)
| | 0
| | >>> x.item((0, 1))
| | 2
| | >>> x.item((2, 2))
| | 1
| |
| | For an array with object dtype, elements are returned as-is.
| |
| | >>> a = np.array([np.int64(1)], dtype=object)
| | >>> a.item() #return np.int64
| | np.int64(1)
| |
| | nonzero(...)
| | a.nonzero()
| |
| | Return the indices of the elements that are non-zero.
| |
| | Refer to `numpy.nonzero` for full documentation.
| |
| | See Also
| | --------
| | numpy.nonzero : equivalent function
| |
| | partition(...)
| | a.partition(kth, axis=-1, kind='introselect', order=None)
| |
| | Partially sorts the elements in the array 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. In the output array, all elements smaller than the k-th element
| | are located to the left of this element and all equal or greater are
| | located to its right. The ordering of the elements in the two partitions
| | on the either side of the k-th element in the output array is undefined.
| |
| | .. versionadded:: 1.8.0
| |
| | Parameters
| | ----------
| | kth : int or sequence of ints
| | Element index to partition by. The kth element value 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 kth it will partition all elements
| | indexed by kth of them into their sorted position at once.
| |
| | .. deprecated:: 1.22.0
| | Passing booleans as index is deprecated.
| | axis : int, optional
| | Axis along which to sort. Default is -1, which means sort along the
| | last axis.
| | kind : {'introselect'}, optional
| | Selection algorithm. Default is 'introselect'.
| | order : str 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, and not all fields need to be specified,
| | but unspecified fields will still be used, in the order in which
| | they come up in the dtype, to break ties.
| |
| | See Also
| | --------
| | numpy.partition : Return a partitioned copy of an array.
| | argpartition : Indirect partition.
| | sort : Full sort.
| |
| | Notes
| | -----
| | See ``np.partition`` for notes on the different algorithms.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.array([3, 4, 2, 1])
| | >>> a.partition(3)
| | >>> a
| | array([2, 1, 3, 4]) # may vary
| |
| | >>> a.partition((1, 3))
| | >>> a
| | array([1, 2, 3, 4])
| |
| | put(...)
| | a.put(indices, values, mode='raise')
| |
| | Set ``a.flat[n] = values[n]`` for all `n` in indices.
| |
| | Refer to `numpy.put` for full documentation.
| |
| | See Also
| | --------
| | numpy.put : equivalent function
| |
| | repeat(...)
| | a.repeat(repeats, axis=None)
| |
| | Repeat elements of an array.
| |
| | Refer to `numpy.repeat` for full documentation.
| |
| | See Also
| | --------
| | numpy.repeat : equivalent function
| |
| | reshape(...)
| | a.reshape(shape, /, *, order='C', copy=None)
| |
| | Returns an array containing the same data with a new shape.
| |
| | Refer to `numpy.reshape` for full documentation.
| |
| | See Also
| | --------
| | numpy.reshape : equivalent function
| |
| | Notes
| | -----
| | Unlike the free function `numpy.reshape`, this method on `ndarray` allows
| | the elements of the shape parameter to be passed in as separate arguments.
| | For example, ``a.reshape(10, 11)`` is equivalent to
| | ``a.reshape((10, 11))``.
| |
| | resize(...)
| | a.resize(new_shape, refcheck=True)
| |
| | Change shape and size of array in-place.
| |
| | Parameters
| | ----------
| | new_shape : tuple of ints, or `n` ints
| | Shape of resized array.
| | refcheck : bool, optional
| | If False, reference count will not be checked. Default is True.
| |
| | Returns
| | -------
| | None
| |
| | Raises
| | ------
| | ValueError
| | If `a` does not own its own data or references or views to it exist,
| | and the data memory must be changed.
| | PyPy only: will always raise if the data memory must be changed, since
| | there is no reliable way to determine if references or views to it
| | exist.
| |
| | SystemError
| | If the `order` keyword argument is specified. This behaviour is a
| | bug in NumPy.
| |
| | See Also
| | --------
| | resize : Return a new array with the specified shape.
| |
| | Notes
| | -----
| | This reallocates space for the data area if necessary.
| |
| | Only contiguous arrays (data elements consecutive in memory) can be
| | resized.
| |
| | The purpose of the reference count check is to make sure you
| | do not use this array as a buffer for another Python object and then
| | reallocate the memory. However, reference counts can increase in
| | other ways so if you are sure that you have not shared the memory
| | for this array with another Python object, then you may safely set
| | `refcheck` to False.
| |
| | Examples
| | --------
| | Shrinking an array: array is flattened (in the order that the data are
| | stored in memory), resized, and reshaped:
| |
| | >>> import numpy as np
| |
| | >>> a = np.array([[0, 1], [2, 3]], order='C')
| | >>> a.resize((2, 1))
| | >>> a
| | array([[0],
| | [1]])
| |
| | >>> a = np.array([[0, 1], [2, 3]], order='F')
| | >>> a.resize((2, 1))
| | >>> a
| | array([[0],
| | [2]])
| |
| | Enlarging an array: as above, but missing entries are filled with zeros:
| |
| | >>> b = np.array([[0, 1], [2, 3]])
| | >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
| | >>> b
| | array([[0, 1, 2],
| | [3, 0, 0]])
| |
| | Referencing an array prevents resizing...
| |
| | >>> c = a
| | >>> a.resize((1, 1))
| | Traceback (most recent call last):
| | ...
| | ValueError: cannot resize an array that references or is referenced ...
| |
| | Unless `refcheck` is False:
| |
| | >>> a.resize((1, 1), refcheck=False)
| | >>> a
| | array([[0]])
| | >>> c
| | array([[0]])
| |
| | round(...)
| | a.round(decimals=0, out=None)
| |
| | Return `a` with each element rounded to the given number of decimals.
| |
| | Refer to `numpy.around` for full documentation.
| |
| | See Also
| | --------
| | numpy.around : equivalent function
| |
| | searchsorted(...)
| | a.searchsorted(v, side='left', sorter=None)
| |
| | Find indices where elements of v should be inserted in a to maintain order.
| |
| | For full documentation, see `numpy.searchsorted`
| |
| | See Also
| | --------
| | numpy.searchsorted : equivalent function
| |
| | setfield(...)
| | a.setfield(val, dtype, offset=0)
| |
| | Put a value into a specified place in a field defined by a data-type.
| |
| | Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| | bytes into the field.
| |
| | Parameters
| | ----------
| | val : object
| | Value to be placed in field.
| | dtype : dtype object
| | Data-type of the field in which to place `val`.
| | offset : int, optional
| | The number of bytes into the field at which to place `val`.
| |
| | Returns
| | -------
| | None
| |
| | See Also
| | --------
| | getfield
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.eye(3)
| | >>> x.getfield(np.float64)
| | array([[1., 0., 0.],
| | [0., 1., 0.],
| | [0., 0., 1.]])
| | >>> x.setfield(3, np.int32)
| | >>> x.getfield(np.int32)
| | array([[3, 3, 3],
| | [3, 3, 3],
| | [3, 3, 3]], dtype=int32)
| | >>> x
| | array([[1.0e+000, 1.5e-323, 1.5e-323],
| | [1.5e-323, 1.0e+000, 1.5e-323],
| | [1.5e-323, 1.5e-323, 1.0e+000]])
| | >>> x.setfield(np.eye(3), np.int32)
| | >>> x
| | array([[1., 0., 0.],
| | [0., 1., 0.],
| | [0., 0., 1.]])
| |
| | setflags(...)
| | a.setflags(write=None, align=None, uic=None)
| |
| | Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| | respectively.
| |
| | These Boolean-valued flags affect how numpy interprets the memory
| | area used by `a` (see Notes below). The ALIGNED flag can only
| | be set to True if the data is actually aligned according to the type.
| | The WRITEBACKIFCOPY flag can never be set
| | to True. The flag WRITEABLE can only be set to True if the array owns its
| | own memory, or the ultimate owner of the memory exposes a writeable buffer
| | interface, or is a string. (The exception for string is made so that
| | unpickling can be done without copying memory.)
| |
| | Parameters
| | ----------
| | write : bool, optional
| | Describes whether or not `a` can be written to.
| | align : bool, optional
| | Describes whether or not `a` is aligned properly for its type.
| | uic : bool, optional
| | Describes whether or not `a` is a copy of another "base" array.
| |
| | Notes
| | -----
| | Array flags provide information about how the memory area used
| | for the array is to be interpreted. There are 7 Boolean flags
| | in use, only three of which can be changed by the user:
| | WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
| |
| | WRITEABLE (W) the data area can be written to;
| |
| | ALIGNED (A) the data and strides are aligned appropriately for the hardware
| | (as determined by the compiler);
| |
| | WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| | by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| | called, the base array will be updated with the contents of this array.
| |
| | All flags can be accessed using the single (upper case) letter as well
| | as the full name.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> y = np.array([[3, 1, 7],
| | ... [2, 0, 0],
| | ... [8, 5, 9]])
| | >>> y
| | array([[3, 1, 7],
| | [2, 0, 0],
| | [8, 5, 9]])
| | >>> y.flags
| | C_CONTIGUOUS : True
| | F_CONTIGUOUS : False
| | OWNDATA : True
| | WRITEABLE : True
| | ALIGNED : True
| | WRITEBACKIFCOPY : False
| | >>> y.setflags(write=0, align=0)
| | >>> y.flags
| | C_CONTIGUOUS : True
| | F_CONTIGUOUS : False
| | OWNDATA : True
| | WRITEABLE : False
| | ALIGNED : False
| | WRITEBACKIFCOPY : False
| | >>> y.setflags(uic=1)
| | Traceback (most recent call last):
| | File "<stdin>", line 1, in <module>
| | ValueError: cannot set WRITEBACKIFCOPY flag to True
| |
| | sort(...)
| | a.sort(axis=-1, kind=None, order=None)
| |
| | Sort an array in-place. Refer to `numpy.sort` for full documentation.
| |
| | Parameters
| | ----------
| | axis : int, optional
| | Axis along which to sort. Default is -1, which means sort along the
| | last axis.
| | kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| | Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
| | and 'mergesort' use timsort under the covers and, in general, the
| | actual implementation will vary with datatype. The 'mergesort' option
| | is retained for backwards compatibility.
| |
| | .. versionchanged:: 1.15.0
| | The 'stable' option was added.
| |
| | order : str 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, and 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.
| |
| | See Also
| | --------
| | numpy.sort : Return a sorted copy of an array.
| | numpy.argsort : Indirect sort.
| | numpy.lexsort : Indirect stable sort on multiple keys.
| | numpy.searchsorted : Find elements in sorted array.
| | numpy.partition: Partial sort.
| |
| | Notes
| | -----
| | See `numpy.sort` for notes on the different sorting algorithms.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.array([[1,4], [3,1]])
| | >>> a.sort(axis=1)
| | >>> a
| | array([[1, 4],
| | [1, 3]])
| | >>> a.sort(axis=0)
| | >>> a
| | array([[1, 3],
| | [1, 4]])
| |
| | Use the `order` keyword to specify a field to use when sorting a
| | structured array:
| |
| | >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
| | >>> a.sort(order='y')
| | >>> a
| | array([(b'c', 1), (b'a', 2)],
| | dtype=[('x', 'S1'), ('y', '<i8')])
| |
| | swapaxes(...)
| | a.swapaxes(axis1, axis2)
| |
| | Return a view of the array with `axis1` and `axis2` interchanged.
| |
| | Refer to `numpy.swapaxes` for full documentation.
| |
| | See Also
| | --------
| | numpy.swapaxes : equivalent function
| |
| | take(...)
| | a.take(indices, axis=None, out=None, mode='raise')
| |
| | Return an array formed from the elements of `a` at the given indices.
| |
| | Refer to `numpy.take` for full documentation.
| |
| | See Also
| | --------
| | numpy.take : equivalent function
| |
| | to_device(...)
| |
| | tobytes(...)
| | a.tobytes(order='C')
| |
| | Construct Python bytes containing the raw data bytes in the array.
| |
| | Constructs Python bytes showing a copy of the raw contents of
| | data memory. The bytes object is produced in C-order by default.
| | This behavior is controlled by the ``order`` parameter.
| |
| | .. versionadded:: 1.9.0
| |
| | Parameters
| | ----------
| | order : {'C', 'F', 'A'}, optional
| | Controls the memory layout of the bytes object. 'C' means C-order,
| | 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
| | Fortran contiguous, 'C' otherwise. Default is 'C'.
| |
| | Returns
| | -------
| | s : bytes
| | Python bytes exhibiting a copy of `a`'s raw data.
| |
| | See also
| | --------
| | frombuffer
| | Inverse of this operation, construct a 1-dimensional array from Python
| | bytes.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
| | >>> x.tobytes()
| | b'\x00\x00\x01\x00\x02\x00\x03\x00'
| | >>> x.tobytes('C') == x.tobytes()
| | True
| | >>> x.tobytes('F')
| | b'\x00\x00\x02\x00\x01\x00\x03\x00'
| |
| | tofile(...)
| | a.tofile(fid, sep="", format="%s")
| |
| | Write array to a file as text or binary (default).
| |
| | Data is always written in 'C' order, independent of the order of `a`.
| | The data produced by this method can be recovered using the function
| | fromfile().
| |
| | Parameters
| | ----------
| | fid : file or str or Path
| | An open file object, or a string containing a filename.
| |
| | .. versionchanged:: 1.17.0
| | `pathlib.Path` objects are now accepted.
| |
| | sep : str
| | Separator between array items for text output.
| | If "" (empty), a binary file is written, equivalent to
| | ``file.write(a.tobytes())``.
| | format : str
| | Format string for text file output.
| | Each entry in the array is formatted to text by first converting
| | it to the closest Python type, and then using "format" % item.
| |
| | Notes
| | -----
| | This is a convenience function for quick storage of array data.
| | Information on endianness and precision is lost, so this method is not a
| | good choice for files intended to archive data or transport data between
| | machines with different endianness. Some of these problems can be overcome
| | by outputting the data as text files, at the expense of speed and file
| | size.
| |
| | When fid is a file object, array contents are directly written to the
| | file, bypassing the file object's ``write`` method. As a result, tofile
| | cannot be used with files objects supporting compression (e.g., GzipFile)
| | or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
| |
| | tostring(...)
| | a.tostring(order='C')
| |
| | A compatibility alias for `~ndarray.tobytes`, with exactly the same
| | behavior.
| |
| | Despite its name, it returns :class:`bytes` not :class:`str`\ s.
| |
| | .. deprecated:: 1.19.0
| |
| | trace(...)
| | a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
| |
| | Return the sum along diagonals of the array.
| |
| | Refer to `numpy.trace` for full documentation.
| |
| | See Also
| | --------
| | numpy.trace : equivalent function
| |
| | transpose(...)
| | a.transpose(*axes)
| |
| | Returns a view of the array with axes transposed.
| |
| | Refer to `numpy.transpose` for full documentation.
| |
| | Parameters
| | ----------
| | axes : None, tuple of ints, or `n` ints
| |
| | * None or no argument: reverses the order of the axes.
| |
| | * tuple of ints: `i` in the `j`-th place in the tuple means that the
| | array's `i`-th axis becomes the transposed array's `j`-th axis.
| |
| | * `n` ints: same as an n-tuple of the same ints (this form is
| | intended simply as a "convenience" alternative to the tuple form).
| |
| | Returns
| | -------
| | p : ndarray
| | View of the array with its axes suitably permuted.
| |
| | See Also
| | --------
| | transpose : Equivalent function.
| | ndarray.T : Array property returning the array transposed.
| | ndarray.reshape : Give a new shape to an array without changing its data.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.array([[1, 2], [3, 4]])
| | >>> a
| | array([[1, 2],
| | [3, 4]])
| | >>> a.transpose()
| | array([[1, 3],
| | [2, 4]])
| | >>> a.transpose((1, 0))
| | array([[1, 3],
| | [2, 4]])
| | >>> a.transpose(1, 0)
| | array([[1, 3],
| | [2, 4]])
| |
| | >>> a = np.array([1, 2, 3, 4])
| | >>> a
| | array([1, 2, 3, 4])
| | >>> a.transpose()
| | array([1, 2, 3, 4])
| |
| | view(...)
| | a.view([dtype][, type])
| |
| | New view of array with the same data.
| |
| | .. note::
| | Passing None for ``dtype`` is different from omitting the parameter,
| | since the former invokes ``dtype(None)`` which is an alias for
| | ``dtype('float64')``.
| |
| | Parameters
| | ----------
| | dtype : data-type or ndarray sub-class, optional
| | Data-type descriptor of the returned view, e.g., float32 or int16.
| | Omitting it results in the view having the same data-type as `a`.
| | This argument can also be specified as an ndarray sub-class, which
| | then specifies the type of the returned object (this is equivalent to
| | setting the ``type`` parameter).
| | type : Python type, optional
| | Type of the returned view, e.g., ndarray or matrix. Again, omission
| | of the parameter results in type preservation.
| |
| | Notes
| | -----
| | ``a.view()`` is used two different ways:
| |
| | ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| | of the array's memory with a different data-type. This can cause a
| | reinterpretation of the bytes of memory.
| |
| | ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| | returns an instance of `ndarray_subclass` that looks at the same array
| | (same shape, dtype, etc.) This does not cause a reinterpretation of the
| | memory.
| |
| | For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| | bytes per entry than the previous dtype (for example, converting a regular
| | array to a structured array), then the last axis of ``a`` must be
| | contiguous. This axis will be resized in the result.
| |
| | .. versionchanged:: 1.23.0
| | Only the last axis needs to be contiguous. Previously, the entire array
| | had to be C-contiguous.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
| |
| | Viewing array data using a different type and dtype:
| |
| | >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
| | >>> y = x.view(dtype=nonneg, type=np.recarray)
| | >>> x["a"]
| | array([-1], dtype=int8)
| | >>> y.a
| | array([255], dtype=uint8)
| |
| | Creating a view on a structured array so it can be used in calculations
| |
| | >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
| | >>> xv = x.view(dtype=np.int8).reshape(-1,2)
| | >>> xv
| | array([[1, 2],
| | [3, 4]], dtype=int8)
| | >>> xv.mean(0)
| | array([2., 3.])
| |
| | Making changes to the view changes the underlying array
| |
| | >>> xv[0,1] = 20
| | >>> x
| | array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
| |
| | Using a view to convert an array to a recarray:
| |
| | >>> z = x.view(np.recarray)
| | >>> z.a
| | array([1, 3], dtype=int8)
| |
| | Views share data:
| |
| | >>> x[0] = (9, 10)
| | >>> z[0]
| | np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
| |
| | Views that change the dtype size (bytes per entry) should normally be
| | avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
| |
| | >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
| | >>> y = x[:, ::2]
| | >>> y
| | array([[1, 3],
| | [4, 6]], dtype=int16)
| | >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
| | Traceback (most recent call last):
| | ...
| | ValueError: To change to a dtype of a different size, the last axis must be contiguous
| | >>> z = y.copy()
| | >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
| | array([[(1, 3)],
| | [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
| |
| | However, views that change dtype are totally fine for arrays with a
| | contiguous last axis, even if the rest of the axes are not C-contiguous:
| |
| | >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
| | >>> x.transpose(1, 0, 2).view(np.int16)
| | array([[[ 256, 770],
| | [3340, 3854]],
| | <BLANKLINE>
| | [[1284, 1798],
| | [4368, 4882]],
| | <BLANKLINE>
| | [[2312, 2826],
| | [5396, 5910]]], dtype=int16)
| |
| | ----------------------------------------------------------------------
| | Class methods inherited from ndarray:
| |
| | __class_getitem__(...)
| | a.__class_getitem__(item, /)
| |
| | Return a parametrized wrapper around the `~numpy.ndarray` type.
| |
| | .. versionadded:: 1.22
| |
| | Returns
| | -------
| | alias : types.GenericAlias
| | A parametrized `~numpy.ndarray` type.
| |
| | Examples
| | --------
| | >>> from typing import Any
| | >>> import numpy as np
| |
| | >>> np.ndarray[Any, np.dtype[Any]]
| | numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
| |
| | See Also
| | --------
| | :pep:`585` : Type hinting generics in standard collections.
| | numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| | w.r.t. its `dtype.type <numpy.dtype.type>`.
| |
| | ----------------------------------------------------------------------
| | Data descriptors inherited from ndarray:
| |
| | __array_interface__
| | Array protocol: Python side.
| |
| | __array_struct__
| | Array protocol: C-struct side.
| |
| | base
| | Base object if memory is from some other object.
| |
| | Examples
| | --------
| | The base of an array that owns its memory is None:
| |
| | >>> import numpy as np
| | >>> x = np.array([1,2,3,4])
| | >>> x.base is None
| | True
| |
| | Slicing creates a view, whose memory is shared with x:
| |
| | >>> y = x[2:]
| | >>> y.base is x
| | True
| |
| | ctypes
| | An object to simplify the interaction of the array with the ctypes
| | module.
| |
| | This attribute creates an object that makes it easier to use arrays
| | when calling shared libraries with the ctypes module. The returned
| | object has, among others, data, shape, and strides attributes (see
| | Notes below) which themselves return ctypes objects that can be used
| | as arguments to a shared library.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | c : Python object
| | Possessing attributes data, shape, strides, etc.
| |
| | See Also
| | --------
| | numpy.ctypeslib
| |
| | Notes
| | -----
| | Below are the public attributes of this object which were documented
| | in "Guide to NumPy" (we have omitted undocumented public attributes,
| | as well as documented private attributes):
| |
| | .. autoattribute:: numpy._core._internal._ctypes.data
| | :noindex:
| |
| | .. autoattribute:: numpy._core._internal._ctypes.shape
| | :noindex:
| |
| | .. autoattribute:: numpy._core._internal._ctypes.strides
| | :noindex:
| |
| | .. automethod:: numpy._core._internal._ctypes.data_as
| | :noindex:
| |
| | .. automethod:: numpy._core._internal._ctypes.shape_as
| | :noindex:
| |
| | .. automethod:: numpy._core._internal._ctypes.strides_as
| | :noindex:
| |
| | If the ctypes module is not available, then the ctypes attribute
| | of array objects still returns something useful, but ctypes objects
| | are not returned and errors may be raised instead. In particular,
| | the object will still have the ``as_parameter`` attribute which will
| | return an integer equal to the data attribute.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> import ctypes
| | >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| | >>> x
| | array([[0, 1],
| | [2, 3]], dtype=int32)
| | >>> x.ctypes.data
| | 31962608 # may vary
| | >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| | <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| | >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| | c_uint(0)
| | >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| | c_ulong(4294967296)
| | >>> x.ctypes.shape
| | <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| | >>> x.ctypes.strides
| | <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
| |
| | data
| | Python buffer object pointing to the start of the array's data.
| |
| | device
| |
| | dtype
| | Data-type of the array's elements.
| |
| | .. warning::
| |
| | Setting ``arr.dtype`` is discouraged and may be deprecated in the
| | future. Setting will replace the ``dtype`` without modifying the
| | memory (see also `ndarray.view` and `ndarray.astype`).
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | d : numpy dtype object
| |
| | See Also
| | --------
| | ndarray.astype : Cast the values contained in the array to a new data-type.
| | ndarray.view : Create a view of the same data but a different data-type.
| | numpy.dtype
| |
| | Examples
| | --------
| | >>> x
| | array([[0, 1],
| | [2, 3]])
| | >>> x.dtype
| | dtype('int32')
| | >>> type(x.dtype)
| | <type 'numpy.dtype'>
| |
| | flags
| | Information about the memory layout of the array.
| |
| | Attributes
| | ----------
| | C_CONTIGUOUS (C)
| | The data is in a single, C-style contiguous segment.
| | F_CONTIGUOUS (F)
| | The data is in a single, Fortran-style contiguous segment.
| | OWNDATA (O)
| | The array owns the memory it uses or borrows it from another object.
| | WRITEABLE (W)
| | The data area can be written to. Setting this to False locks
| | the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| | from its base array at creation time, but a view of a writeable
| | array may be subsequently locked while the base array remains writeable.
| | (The opposite is not true, in that a view of a locked array may not
| | be made writeable. However, currently, locking a base object does not
| | lock any views that already reference it, so under that circumstance it
| | is possible to alter the contents of a locked array via a previously
| | created writeable view onto it.) Attempting to change a non-writeable
| | array raises a RuntimeError exception.
| | ALIGNED (A)
| | The data and all elements are aligned appropriately for the hardware.
| | WRITEBACKIFCOPY (X)
| | This array is a copy of some other array. The C-API function
| | PyArray_ResolveWritebackIfCopy must be called before deallocating
| | to the base array will be updated with the contents of this array.
| | FNC
| | F_CONTIGUOUS and not C_CONTIGUOUS.
| | FORC
| | F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| | BEHAVED (B)
| | ALIGNED and WRITEABLE.
| | CARRAY (CA)
| | BEHAVED and C_CONTIGUOUS.
| | FARRAY (FA)
| | BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
| |
| | Notes
| | -----
| | The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| | or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| | names are only supported in dictionary access.
| |
| | Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| | changed by the user, via direct assignment to the attribute or dictionary
| | entry, or by calling `ndarray.setflags`.
| |
| | The array flags cannot be set arbitrarily:
| |
| | - WRITEBACKIFCOPY can only be set ``False``.
| | - ALIGNED can only be set ``True`` if the data is truly aligned.
| | - WRITEABLE can only be set ``True`` if the array owns its own memory
| | or the ultimate owner of the memory exposes a writeable buffer
| | interface or is a string.
| |
| | Arrays can be both C-style and Fortran-style contiguous simultaneously.
| | This is clear for 1-dimensional arrays, but can also be true for higher
| | dimensional arrays.
| |
| | Even for contiguous arrays a stride for a given dimension
| | ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| | or the array has no elements.
| | It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| | for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| | Fortran-style contiguous arrays is true.
| |
| | flat
| | A 1-D iterator over the array.
| |
| | This is a `numpy.flatiter` instance, which acts similarly to, but is not
| | a subclass of, Python's built-in iterator object.
| |
| | See Also
| | --------
| | flatten : Return a copy of the array collapsed into one dimension.
| |
| | flatiter
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.arange(1, 7).reshape(2, 3)
| | >>> x
| | array([[1, 2, 3],
| | [4, 5, 6]])
| | >>> x.flat[3]
| | 4
| | >>> x.T
| | array([[1, 4],
| | [2, 5],
| | [3, 6]])
| | >>> x.T.flat[3]
| | 5
| | >>> type(x.flat)
| | <class 'numpy.flatiter'>
| |
| | An assignment example:
| |
| | >>> x.flat = 3; x
| | array([[3, 3, 3],
| | [3, 3, 3]])
| | >>> x.flat[[1,4]] = 1; x
| | array([[3, 1, 3],
| | [3, 1, 3]])
| |
| | imag
| | The imaginary part of the array.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.sqrt([1+0j, 0+1j])
| | >>> x.imag
| | array([ 0. , 0.70710678])
| | >>> x.imag.dtype
| | dtype('float64')
| |
| | itemset
| |
| | itemsize
| | Length of one array element in bytes.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([1,2,3], dtype=np.float64)
| | >>> x.itemsize
| | 8
| | >>> x = np.array([1,2,3], dtype=np.complex128)
| | >>> x.itemsize
| | 16
| |
| | mT
| | View of the matrix transposed array.
| |
| | The matrix transpose is the transpose of the last two dimensions, even
| | if the array is of higher dimension.
| |
| | .. versionadded:: 2.0
| |
| | Raises
| | ------
| | ValueError
| | If the array is of dimension less than 2.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.array([[1, 2], [3, 4]])
| | >>> a
| | array([[1, 2],
| | [3, 4]])
| | >>> a.mT
| | array([[1, 3],
| | [2, 4]])
| |
| | >>> a = np.arange(8).reshape((2, 2, 2))
| | >>> a
| | array([[[0, 1],
| | [2, 3]],
| | <BLANKLINE>
| | [[4, 5],
| | [6, 7]]])
| | >>> a.mT
| | array([[[0, 2],
| | [1, 3]],
| | <BLANKLINE>
| | [[4, 6],
| | [5, 7]]])
| |
| | nbytes
| | Total bytes consumed by the elements of the array.
| |
| | Notes
| | -----
| | Does not include memory consumed by non-element attributes of the
| | array object.
| |
| | See Also
| | --------
| | sys.getsizeof
| | Memory consumed by the object itself without parents in case view.
| | This does include memory consumed by non-element attributes.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.zeros((3,5,2), dtype=np.complex128)
| | >>> x.nbytes
| | 480
| | >>> np.prod(x.shape) * x.itemsize
| | 480
| |
| | ndim
| | Number of array dimensions.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([1, 2, 3])
| | >>> x.ndim
| | 1
| | >>> y = np.zeros((2, 3, 4))
| | >>> y.ndim
| | 3
| |
| | newbyteorder
| |
| | real
| | The real part of the array.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.sqrt([1+0j, 0+1j])
| | >>> x.real
| | array([ 1. , 0.70710678])
| | >>> x.real.dtype
| | dtype('float64')
| |
| | See Also
| | --------
| | numpy.real : equivalent function
| |
| | shape
| | Tuple of array dimensions.
| |
| | The shape property is usually used to get the current shape of an array,
| | but may also be used to reshape the array in-place by assigning a tuple of
| | array dimensions to it. As with `numpy.reshape`, one of the new shape
| | dimensions can be -1, in which case its value is inferred from the size of
| | the array and the remaining dimensions. Reshaping an array in-place will
| | fail if a copy is required.
| |
| | .. warning::
| |
| | Setting ``arr.shape`` is discouraged and may be deprecated in the
| | future. Using `ndarray.reshape` is the preferred approach.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([1, 2, 3, 4])
| | >>> x.shape
| | (4,)
| | >>> y = np.zeros((2, 3, 4))
| | >>> y.shape
| | (2, 3, 4)
| | >>> y.shape = (3, 8)
| | >>> y
| | array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| | [ 0., 0., 0., 0., 0., 0., 0., 0.],
| | [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| | >>> y.shape = (3, 6)
| | Traceback (most recent call last):
| | File "<stdin>", line 1, in <module>
| | ValueError: total size of new array must be unchanged
| | >>> np.zeros((4,2))[::2].shape = (-1,)
| | Traceback (most recent call last):
| | File "<stdin>", line 1, in <module>
| | AttributeError: Incompatible shape for in-place modification. Use
| | `.reshape()` to make a copy with the desired shape.
| |
| | See Also
| | --------
| | numpy.shape : Equivalent getter function.
| | numpy.reshape : Function similar to setting ``shape``.
| | ndarray.reshape : Method similar to setting ``shape``.
| |
| | size
| | Number of elements in the array.
| |
| | Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| | dimensions.
| |
| | Notes
| | -----
| | `a.size` returns a standard arbitrary precision Python integer. This
| | may not be the case with other methods of obtaining the same value
| | (like the suggested ``np.prod(a.shape)``, which returns an instance
| | of ``np.int_``), and may be relevant if the value is used further in
| | calculations that may overflow a fixed size integer type.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| | >>> x.size
| | 30
| | >>> np.prod(x.shape)
| | 30
| |
| | strides
| | Tuple of bytes to step in each dimension when traversing an array.
| |
| | The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| | is::
| |
| | offset = sum(np.array(i) * a.strides)
| |
| | A more detailed explanation of strides can be found in
| | :ref:`arrays.ndarray`.
| |
| | .. warning::
| |
| | Setting ``arr.strides`` is discouraged and may be deprecated in the
| | future. `numpy.lib.stride_tricks.as_strided` should be preferred
| | to create a new view of the same data in a safer way.
| |
| | Notes
| | -----
| | Imagine an array of 32-bit integers (each 4 bytes)::
| |
| | x = np.array([[0, 1, 2, 3, 4],
| | [5, 6, 7, 8, 9]], dtype=np.int32)
| |
| | This array is stored in memory as 40 bytes, one after the other
| | (known as a contiguous block of memory). The strides of an array tell
| | us how many bytes we have to skip in memory to move to the next position
| | along a certain axis. For example, we have to skip 4 bytes (1 value) to
| | move to the next column, but 20 bytes (5 values) to get to the same
| | position in the next row. As such, the strides for the array `x` will be
| | ``(20, 4)``.
| |
| | See Also
| | --------
| | numpy.lib.stride_tricks.as_strided
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| | >>> y
| | array([[[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]],
| | [[12, 13, 14, 15],
| | [16, 17, 18, 19],
| | [20, 21, 22, 23]]])
| | >>> y.strides
| | (48, 16, 4)
| | >>> y[1,1,1]
| | 17
| | >>> offset=sum(y.strides * np.array((1,1,1)))
| | >>> offset/y.itemsize
| | 17
| |
| | >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| | >>> x.strides
| | (32, 4, 224, 1344)
| | >>> i = np.array([3,5,2,2])
| | >>> offset = sum(i * x.strides)
| | >>> x[3,5,2,2]
| | 813
| | >>> offset / x.itemsize
| | 813
| |
| | ----------------------------------------------------------------------
| | Data and other attributes inherited from ndarray:
| |
| | __hash__ = None
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AxisConcatenator:
|
| axis
|
| matrix
|
| ndmin
|
| trans1d
numpy.can_cast
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
can_cast(...)
can_cast(from_, to, casting='safe')
Returns True if cast between data types can occur according to the
casting rule.
Parameters
----------
from_ : dtype, dtype specifier, NumPy scalar, or array
Data type, NumPy scalar, or array to cast from.
to : dtype or dtype specifier
Data type to cast to.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur.
* '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.
Returns
-------
out : bool
True if cast can occur according to the casting rule.
Notes
-----
.. versionchanged:: 1.17.0
Casting between a simple data type and a structured one is possible only
for "unsafe" casting. Casting to multiple fields is allowed, but
casting from multiple fields is not.
.. versionchanged:: 1.9.0
Casting from numeric to string types in 'safe' casting mode requires
that the string dtype length is long enough to store the maximum
integer/float value converted.
.. versionchanged:: 2.0
This function does not support Python scalars anymore and does not
apply any value-based logic for 0-D arrays and NumPy scalars.
See also
--------
dtype, result_type
Examples
--------
Basic examples
>>> import numpy as np
>>> np.can_cast(np.int32, np.int64)
True
>>> np.can_cast(np.float64, complex)
True
>>> np.can_cast(complex, float)
False
>>> np.can_cast('i8', 'f8')
True
>>> np.can_cast('i8', 'f4')
False
>>> np.can_cast('i4', 'S4')
False
numpy.cbrt
Python Library Documentation: ufunc
cbrt = <ufunc 'cbrt'>
cbrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the cube-root of an array, element-wise.
.. versionadded:: 1.10.0
Parameters
----------
x : array_like
The values whose cube-roots are required.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
An array of the same shape as `x`, containing the
cube root of each element in `x`.
If `out` was provided, `y` is a reference to it.
This is a scalar if `x` is a scalar.
Examples
--------
>>> import numpy as np
>>> np.cbrt([1,8,27])
array([ 1., 2., 3.])
numpy.cdouble
Python Library Documentation: class complex128 in module numpy class complex128(complexfloating, builtins.complex) | complex128(real=0, imag=0) | | Complex number type composed of two double-precision floating-point | numbers, compatible with Python :class:`complex`. | | :Character code: ``'D'`` | :Canonical name: `numpy.cdouble` | :Alias on this platform (win32 AMD64): `numpy.complex128`: Complex number type composed of 2 64-bit-precision floating-point numbers. | | Method resolution order: | complex128 | complexfloating | inexact | number | generic | builtins.complex | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from complexfloating: | | __round__(...) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __reduce__(...) | Helper for pickle. | | __rlshift__(self, value, /) | Return value<<self. | | __ror__(self, value, /) | Return value|self. | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Methods inherited from builtins.complex: | | __complex__(self, /) | Convert this value to exact type complex. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(self, /)
numpy.ceil
Python Library Documentation: ufunc
ceil = <ufunc 'ceil'>
ceil(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the ceiling of the input, element-wise.
The ceil of the scalar `x` is the smallest integer `i`, such that
``i >= x``. It is often denoted as :math:`\lceil x \rceil`.
Parameters
----------
x : array_like
Input data.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The ceiling of each element in `x`.
This is a scalar if `x` is a scalar.
See Also
--------
floor, trunc, rint, fix
Examples
--------
>>> import numpy as np
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.ceil(a)
array([-1., -1., -0., 1., 2., 2., 2.])
numpy.char
Python Library Documentation: package numpy.char in numpy
NAME
numpy.char
DESCRIPTION
This module contains a set of functions for vectorized string
operations and methods.
.. note::
The `chararray` class exists for backwards compatibility with
Numarray, it is not recommended for new development. Starting from numpy
1.4, if one needs arrays of strings, it is recommended to use arrays of
`dtype` `object_`, `bytes_` or `str_`, and use the free functions
in the `numpy.char` module for fast vectorized string operations.
Some methods will only be available if the corresponding string method is
available in your version of Python.
The preferred alias for `defchararray` is `numpy.char`.
PACKAGE CONTENTS
CLASSES
numpy.ndarray(builtins.object)
chararray
class chararray(numpy.ndarray)
| chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order='C')
|
| chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,
| strides=None, order=None)
|
| Provides a convenient view on arrays of string and unicode values.
|
| .. note::
| The `chararray` class exists for backwards compatibility with
| Numarray, it is not recommended for new development. Starting from numpy
| 1.4, if one needs arrays of strings, it is recommended to use arrays of
| `dtype` `~numpy.object_`, `~numpy.bytes_` or `~numpy.str_`, and use
| the free functions in the `numpy.char` module for fast vectorized
| string operations.
|
| Versus a NumPy array of dtype `~numpy.bytes_` or `~numpy.str_`, this
| class adds the following functionality:
|
| 1) values automatically have whitespace removed from the end
| when indexed
|
| 2) comparison operators automatically remove whitespace from the
| end when comparing values
|
| 3) vectorized string operations are provided as methods
| (e.g. `.endswith`) and infix operators (e.g. ``"+", "*", "%"``)
|
| chararrays should be created using `numpy.char.array` or
| `numpy.char.asarray`, rather than this constructor directly.
|
| This constructor creates the array, using `buffer` (with `offset`
| and `strides`) if it is not ``None``. If `buffer` is ``None``, then
| constructs a new array with `strides` in "C order", unless both
| ``len(shape) >= 2`` and ``order='F'``, in which case `strides`
| is in "Fortran order".
|
| Methods
| -------
| astype
| argsort
| copy
| count
| decode
| dump
| dumps
| encode
| endswith
| expandtabs
| fill
| find
| flatten
| getfield
| index
| isalnum
| isalpha
| isdecimal
| isdigit
| islower
| isnumeric
| isspace
| istitle
| isupper
| item
| join
| ljust
| lower
| lstrip
| nonzero
| put
| ravel
| repeat
| replace
| reshape
| resize
| rfind
| rindex
| rjust
| rsplit
| rstrip
| searchsorted
| setfield
| setflags
| sort
| split
| splitlines
| squeeze
| startswith
| strip
| swapaxes
| swapcase
| take
| title
| tofile
| tolist
| tostring
| translate
| transpose
| upper
| view
| zfill
|
| Parameters
| ----------
| shape : tuple
| Shape of the array.
| itemsize : int, optional
| Length of each array element, in number of characters. Default is 1.
| unicode : bool, optional
| Are the array elements of type unicode (True) or string (False).
| Default is False.
| buffer : object exposing the buffer interface or str, optional
| Memory address of the start of the array data. Default is None,
| in which case a new array is created.
| offset : int, optional
| Fixed stride displacement from the beginning of an axis?
| Default is 0. Needs to be >=0.
| strides : array_like of ints, optional
| Strides for the array (see `~numpy.ndarray.strides` for
| full description). Default is None.
| order : {'C', 'F'}, optional
| The order in which the array data is stored in memory: 'C' ->
| "row major" order (the default), 'F' -> "column major"
| (Fortran) order.
|
| Examples
| --------
| >>> import numpy as np
| >>> charar = np.char.chararray((3, 3))
| >>> charar[:] = 'a'
| >>> charar
| chararray([[b'a', b'a', b'a'],
| [b'a', b'a', b'a'],
| [b'a', b'a', b'a']], dtype='|S1')
|
| >>> charar = np.char.chararray(charar.shape, itemsize=5)
| >>> charar[:] = 'abc'
| >>> charar
| chararray([[b'abc', b'abc', b'abc'],
| [b'abc', b'abc', b'abc'],
| [b'abc', b'abc', b'abc']], dtype='|S5')
|
| Method resolution order:
| chararray
| numpy.ndarray
| builtins.object
|
| Methods defined here:
|
| __add__(self, other) from numpy._core.defchararray.chararray
| Return (self + other), that is string concatenation,
| element-wise for a pair of array_likes of str or unicode.
|
| See Also
| --------
| add
|
| __array_finalize__(self, obj) from numpy._core.defchararray.chararray
| a.__array_finalize__(obj, /)
|
| Present so subclasses can call super. Does nothing.
|
| __array_wrap__(self, arr, context=None, return_scalar=False) from numpy._core.defchararray.chararray
| a.__array_wrap__(array[, context], /)
|
| Returns a view of `array` with the same type as self.
|
| __eq__(self, other) from numpy._core.defchararray.chararray
| Return (self == other) element-wise.
|
| See Also
| --------
| equal
|
| __ge__(self, other) from numpy._core.defchararray.chararray
| Return (self >= other) element-wise.
|
| See Also
| --------
| greater_equal
|
| __getitem__(self, obj) from numpy._core.defchararray.chararray
| Return self[key].
|
| __gt__(self, other) from numpy._core.defchararray.chararray
| Return (self > other) element-wise.
|
| See Also
| --------
| greater
|
| __le__(self, other) from numpy._core.defchararray.chararray
| Return (self <= other) element-wise.
|
| See Also
| --------
| less_equal
|
| __lt__(self, other) from numpy._core.defchararray.chararray
| Return (self < other) element-wise.
|
| See Also
| --------
| less
|
| __mod__(self, i) from numpy._core.defchararray.chararray
| Return (self % i), that is pre-Python 2.6 string formatting
| (interpolation), element-wise for a pair of array_likes of `bytes_`
| or `str_`.
|
| See Also
| --------
| mod
|
| __mul__(self, i) from numpy._core.defchararray.chararray
| Return (self * i), that is string multiple concatenation,
| element-wise.
|
| See Also
| --------
| multiply
|
| __ne__(self, other) from numpy._core.defchararray.chararray
| Return (self != other) element-wise.
|
| See Also
| --------
| not_equal
|
| __radd__(self, other) from numpy._core.defchararray.chararray
| Return (other + self), that is string concatenation,
| element-wise for a pair of array_likes of `bytes_` or `str_`.
|
| See Also
| --------
| add
|
| __rmod__(self, other) from numpy._core.defchararray.chararray
| Return value%self.
|
| __rmul__(self, i) from numpy._core.defchararray.chararray
| Return (self * i), that is string multiple concatenation,
| element-wise.
|
| See Also
| --------
| multiply
|
| argsort(self, axis=-1, kind=None, order=None) from numpy._core.defchararray.chararray
| a.argsort(axis=-1, kind=None, order=None)
|
| Returns the indices that would sort this array.
|
| Refer to `numpy.argsort` for full documentation.
|
| See Also
| --------
| numpy.argsort : equivalent function
|
| capitalize(self) from numpy._core.defchararray.chararray
| Return a copy of `self` with only the first character of each element
| capitalized.
|
| See Also
| --------
| char.capitalize
|
| center(self, width, fillchar=' ') from numpy._core.defchararray.chararray
| Return a copy of `self` with its elements centered in a
| string of length `width`.
|
| See Also
| --------
| center
|
| count(self, sub, start=0, end=None) from numpy._core.defchararray.chararray
| Returns an array with the number of non-overlapping occurrences of
| substring `sub` in the range [`start`, `end`].
|
| See Also
| --------
| char.count
|
| decode(self, encoding=None, errors=None) from numpy._core.defchararray.chararray
| Calls ``bytes.decode`` element-wise.
|
| See Also
| --------
| char.decode
|
| encode(self, encoding=None, errors=None) from numpy._core.defchararray.chararray
| Calls :meth:`str.encode` element-wise.
|
| See Also
| --------
| char.encode
|
| endswith(self, suffix, start=0, end=None) from numpy._core.defchararray.chararray
| Returns a boolean array which is `True` where the string element
| in `self` ends with `suffix`, otherwise `False`.
|
| See Also
| --------
| char.endswith
|
| expandtabs(self, tabsize=8) from numpy._core.defchararray.chararray
| Return a copy of each string element where all tab characters are
| replaced by one or more spaces.
|
| See Also
| --------
| char.expandtabs
|
| find(self, sub, start=0, end=None) from numpy._core.defchararray.chararray
| For each element, return the lowest index in the string where
| substring `sub` is found.
|
| See Also
| --------
| char.find
|
| index(self, sub, start=0, end=None) from numpy._core.defchararray.chararray
| Like `find`, but raises :exc:`ValueError` when the substring is not
| found.
|
| See Also
| --------
| char.index
|
| isalnum(self) from numpy._core.defchararray.chararray
| Returns true for each element if all characters in the string
| are alphanumeric and there is at least one character, false
| otherwise.
|
| See Also
| --------
| char.isalnum
|
| isalpha(self) from numpy._core.defchararray.chararray
| Returns true for each element if all characters in the string
| are alphabetic and there is at least one character, false
| otherwise.
|
| See Also
| --------
| char.isalpha
|
| isdecimal(self) from numpy._core.defchararray.chararray
| For each element in `self`, return True if there are only
| decimal characters in the element.
|
| See Also
| --------
| char.isdecimal
|
| isdigit(self) from numpy._core.defchararray.chararray
| Returns true for each element if all characters in the string are
| digits and there is at least one character, false otherwise.
|
| See Also
| --------
| char.isdigit
|
| islower(self) from numpy._core.defchararray.chararray
| Returns true for each element if all cased characters in the
| string are lowercase and there is at least one cased character,
| false otherwise.
|
| See Also
| --------
| char.islower
|
| isnumeric(self) from numpy._core.defchararray.chararray
| For each element in `self`, return True if there are only
| numeric characters in the element.
|
| See Also
| --------
| char.isnumeric
|
| isspace(self) from numpy._core.defchararray.chararray
| Returns true for each element if there are only whitespace
| characters in the string and there is at least one character,
| false otherwise.
|
| See Also
| --------
| char.isspace
|
| istitle(self) from numpy._core.defchararray.chararray
| Returns true for each element if the element is a titlecased
| string and there is at least one character, false otherwise.
|
| See Also
| --------
| char.istitle
|
| isupper(self) from numpy._core.defchararray.chararray
| Returns true for each element if all cased characters in the
| string are uppercase and there is at least one character, false
| otherwise.
|
| See Also
| --------
| char.isupper
|
| join(self, seq) from numpy._core.defchararray.chararray
| Return a string which is the concatenation of the strings in the
| sequence `seq`.
|
| See Also
| --------
| char.join
|
| ljust(self, width, fillchar=' ') from numpy._core.defchararray.chararray
| Return an array with the elements of `self` left-justified in a
| string of length `width`.
|
| See Also
| --------
| char.ljust
|
| lower(self) from numpy._core.defchararray.chararray
| Return an array with the elements of `self` converted to
| lowercase.
|
| See Also
| --------
| char.lower
|
| lstrip(self, chars=None) from numpy._core.defchararray.chararray
| For each element in `self`, return a copy with the leading characters
| removed.
|
| See Also
| --------
| char.lstrip
|
| partition(self, sep) from numpy._core.defchararray.chararray
| Partition each element in `self` around `sep`.
|
| See Also
| --------
| partition
|
| replace(self, old, new, count=None) from numpy._core.defchararray.chararray
| For each element in `self`, return a copy of the string with all
| occurrences of substring `old` replaced by `new`.
|
| See Also
| --------
| char.replace
|
| rfind(self, sub, start=0, end=None) from numpy._core.defchararray.chararray
| For each element in `self`, return the highest index in the string
| where substring `sub` is found, such that `sub` is contained
| within [`start`, `end`].
|
| See Also
| --------
| char.rfind
|
| rindex(self, sub, start=0, end=None) from numpy._core.defchararray.chararray
| Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
| not found.
|
| See Also
| --------
| char.rindex
|
| rjust(self, width, fillchar=' ') from numpy._core.defchararray.chararray
| Return an array with the elements of `self`
| right-justified in a string of length `width`.
|
| See Also
| --------
| char.rjust
|
| rpartition(self, sep) from numpy._core.defchararray.chararray
| Partition each element in `self` around `sep`.
|
| See Also
| --------
| rpartition
|
| rsplit(self, sep=None, maxsplit=None) from numpy._core.defchararray.chararray
| For each element in `self`, return a list of the words in
| the string, using `sep` as the delimiter string.
|
| See Also
| --------
| char.rsplit
|
| rstrip(self, chars=None) from numpy._core.defchararray.chararray
| For each element in `self`, return a copy with the trailing
| characters removed.
|
| See Also
| --------
| char.rstrip
|
| split(self, sep=None, maxsplit=None) from numpy._core.defchararray.chararray
| For each element in `self`, return a list of the words in the
| string, using `sep` as the delimiter string.
|
| See Also
| --------
| char.split
|
| splitlines(self, keepends=None) from numpy._core.defchararray.chararray
| For each element in `self`, return a list of the lines in the
| element, breaking at line boundaries.
|
| See Also
| --------
| char.splitlines
|
| startswith(self, prefix, start=0, end=None) from numpy._core.defchararray.chararray
| Returns a boolean array which is `True` where the string element
| in `self` starts with `prefix`, otherwise `False`.
|
| See Also
| --------
| char.startswith
|
| strip(self, chars=None) from numpy._core.defchararray.chararray
| For each element in `self`, return a copy with the leading and
| trailing characters removed.
|
| See Also
| --------
| char.strip
|
| swapcase(self) from numpy._core.defchararray.chararray
| For each element in `self`, return a copy of the string with
| uppercase characters converted to lowercase and vice versa.
|
| See Also
| --------
| char.swapcase
|
| title(self) from numpy._core.defchararray.chararray
| For each element in `self`, return a titlecased version of the
| string: words start with uppercase characters, all remaining cased
| characters are lowercase.
|
| See Also
| --------
| char.title
|
| translate(self, table, deletechars=None) from numpy._core.defchararray.chararray
| For each element in `self`, return a copy of the string where
| all characters occurring in the optional argument
| `deletechars` are removed, and the remaining characters have
| been mapped through the given translation table.
|
| See Also
| --------
| char.translate
|
| upper(self) from numpy._core.defchararray.chararray
| Return an array with the elements of `self` converted to
| uppercase.
|
| See Also
| --------
| char.upper
|
| zfill(self, width) from numpy._core.defchararray.chararray
| Return the numeric string left-filled with zeros in a string of
| length `width`.
|
| See Also
| --------
| char.zfill
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(subtype, shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order='C') from numpy._core.defchararray.chararray
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.ndarray:
|
| __abs__(self, /)
| abs(self)
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| a.__array__([dtype], *, copy=None)
|
| For ``dtype`` parameter it returns a new reference to self if
| ``dtype`` is not given or it matches array's data type.
| A new array of provided data type is returned if ``dtype``
| is different from the current data type of the array.
| For ``copy`` parameter it returns a new reference to self if
| ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| parameter. The method returns a new array for ``copy=True``, regardless of
| ``dtype`` parameter.
|
| A more detailed explanation of the ``__array__`` interface
| can be found in :ref:`dunder_array.interface`.
|
| __array_function__(...)
|
| __array_namespace__(...)
|
| __array_ufunc__(...)
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __complex__(...)
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __copy__(...)
| a.__copy__()
|
| Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
|
| Equivalent to ``a.copy(order='K')``.
|
| __deepcopy__(...)
| a.__deepcopy__(memo, /)
|
| Used if :func:`copy.deepcopy` is called on an array.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __dlpack__(...)
| a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
|
| DLPack Protocol: Part of the Array API.
|
| __dlpack_device__(...)
| a.__dlpack_device__()
|
| DLPack Protocol: Part of the Array API.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __iadd__(self, value, /)
| Return self+=value.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __ifloordiv__(self, value, /)
| Return self//=value.
|
| __ilshift__(self, value, /)
| Return self<<=value.
|
| __imatmul__(self, value, /)
| Return self@=value.
|
| __imod__(self, value, /)
| Return self%=value.
|
| __imul__(self, value, /)
| Return self*=value.
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __ior__(self, value, /)
| Return self|=value.
|
| __ipow__(self, value, /)
| Return self**=value.
|
| __irshift__(self, value, /)
| Return self>>=value.
|
| __isub__(self, value, /)
| Return self-=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __itruediv__(self, value, /)
| Return self/=value.
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __len__(self, /)
| Return len(self).
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __matmul__(self, value, /)
| Return self@value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| a.__reduce__()
|
| For pickling.
|
| __reduce_ex__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmatmul__(self, value, /)
| Return value@self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __setstate__(...)
| a.__setstate__(state, /)
|
| For unpickling.
|
| The `state` argument must be a sequence that contains the following
| elements:
|
| Parameters
| ----------
| version : int
| optional pickle version. If omitted defaults to 0.
| shape : tuple
| dtype : data-type
| isFortran : bool
| rawdata : string or list
| a binary string with the data (or a list if 'a' is an object array)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| a.all(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if all elements evaluate to True.
|
| Refer to `numpy.all` for full documentation.
|
| See Also
| --------
| numpy.all : equivalent function
|
| any(...)
| a.any(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if any of the elements of `a` evaluate to True.
|
| Refer to `numpy.any` for full documentation.
|
| See Also
| --------
| numpy.any : equivalent function
|
| argmax(...)
| a.argmax(axis=None, out=None, *, keepdims=False)
|
| Return indices of the maximum values along the given axis.
|
| Refer to `numpy.argmax` for full documentation.
|
| See Also
| --------
| numpy.argmax : equivalent function
|
| argmin(...)
| a.argmin(axis=None, out=None, *, keepdims=False)
|
| Return indices of the minimum values along the given axis.
|
| Refer to `numpy.argmin` for detailed documentation.
|
| See Also
| --------
| numpy.argmin : equivalent function
|
| argpartition(...)
| a.argpartition(kth, axis=-1, kind='introselect', order=None)
|
| Returns the indices that would partition this array.
|
| Refer to `numpy.argpartition` for full documentation.
|
| .. versionadded:: 1.8.0
|
| See Also
| --------
| numpy.argpartition : equivalent function
|
| astype(...)
| a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
|
| Copy of the array, cast to a specified type.
|
| Parameters
| ----------
| dtype : str or dtype
| Typecode or data-type to which the array is cast.
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout order of the result.
| '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.
| Default is 'K'.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'unsafe'
| for backwards compatibility.
|
| * '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.
| subok : bool, optional
| If True, then sub-classes will be passed-through (default), otherwise
| the returned array will be forced to be a base-class array.
| copy : bool, optional
| By default, astype always returns a newly allocated array. If this
| is set to false, and the `dtype`, `order`, and `subok`
| requirements are satisfied, the input array is returned instead
| of a copy.
|
| Returns
| -------
| arr_t : ndarray
| Unless `copy` is False and the other conditions for returning the input
| array are satisfied (see description for `copy` input parameter), `arr_t`
| is a new array of the same shape as the input array, with dtype, order
| given by `dtype`, `order`.
|
| Notes
| -----
| .. versionchanged:: 1.17.0
| Casting between a simple data type and a structured one is possible only
| for "unsafe" casting. Casting to multiple fields is allowed, but
| casting from multiple fields is not.
|
| .. versionchanged:: 1.9.0
| Casting from numeric to string types in 'safe' casting mode requires
| that the string dtype length is long enough to store the max
| integer/float value converted.
|
| Raises
| ------
| ComplexWarning
| When casting from complex to float or int. To avoid this,
| one should use ``a.real.astype(t)``.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 2.5])
| >>> x
| array([1. , 2. , 2.5])
|
| >>> x.astype(int)
| array([1, 2, 2])
|
| byteswap(...)
| a.byteswap(inplace=False)
|
| Swap the bytes of the array elements
|
| Toggle between low-endian and big-endian data representation by
| returning a byteswapped array, optionally swapped in-place.
| Arrays of byte-strings are not swapped. The real and imaginary
| parts of a complex number are swapped individually.
|
| Parameters
| ----------
| inplace : bool, optional
| If ``True``, swap bytes in-place, default is ``False``.
|
| Returns
| -------
| out : ndarray
| The byteswapped array. If `inplace` is ``True``, this is
| a view to self.
|
| Examples
| --------
| >>> import numpy as np
| >>> A = np.array([1, 256, 8755], dtype=np.int16)
| >>> list(map(hex, A))
| ['0x1', '0x100', '0x2233']
| >>> A.byteswap(inplace=True)
| array([ 256, 1, 13090], dtype=int16)
| >>> list(map(hex, A))
| ['0x100', '0x1', '0x3322']
|
| Arrays of byte-strings are not swapped
|
| >>> A = np.array([b'ceg', b'fac'])
| >>> A.byteswap()
| array([b'ceg', b'fac'], dtype='|S3')
|
| ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| the same values but different representation in memory
|
| >>> A = np.array([1, 2, 3])
| >>> A.view(np.uint8)
| array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| 0, 0], dtype=uint8)
| >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| array([1, 2, 3])
| >>> A.view(np.uint8)
| array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| 0, 3], dtype=uint8)
|
| choose(...)
| a.choose(choices, out=None, mode='raise')
|
| Use an index array to construct a new array from a set of choices.
|
| Refer to `numpy.choose` for full documentation.
|
| See Also
| --------
| numpy.choose : equivalent function
|
| clip(...)
| a.clip(min=None, max=None, out=None, **kwargs)
|
| Return an array whose values are limited to ``[min, max]``.
| One of max or min must be given.
|
| Refer to `numpy.clip` for full documentation.
|
| See Also
| --------
| numpy.clip : equivalent function
|
| compress(...)
| a.compress(condition, axis=None, out=None)
|
| Return selected slices of this array along given axis.
|
| Refer to `numpy.compress` for full documentation.
|
| See Also
| --------
| numpy.compress : equivalent function
|
| conj(...)
| a.conj()
|
| Complex-conjugate all elements.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| conjugate(...)
| a.conjugate()
|
| Return the complex conjugate, element-wise.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| copy(...)
| a.copy(order='C')
|
| Return a copy of the array.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout of the copy. 'C' means C-order,
| 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| 'C' otherwise. 'K' means match the layout of `a` as closely
| as possible. (Note that this function and :func:`numpy.copy` are very
| similar but have different default values for their order=
| arguments, and this function always passes sub-classes through.)
|
| See also
| --------
| numpy.copy : Similar function with different default behavior
| numpy.copyto
|
| Notes
| -----
| This function is the preferred method for creating an array copy. The
| function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| and will not pass sub-classes through by default.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[1,2,3],[4,5,6]], order='F')
|
| >>> y = x.copy()
|
| >>> x.fill(0)
|
| >>> x
| array([[0, 0, 0],
| [0, 0, 0]])
|
| >>> y
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> y.flags['C_CONTIGUOUS']
| True
|
| For arrays containing Python objects (e.g. dtype=object),
| the copy is a shallow one. The new array will contain the
| same object which may lead to surprises if that object can
| be modified (is mutable):
|
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> b = a.copy()
| >>> b[2][0] = 10
| >>> a
| array([1, 'm', list([10, 3, 4])], dtype=object)
|
| To ensure all elements within an ``object`` array are copied,
| use `copy.deepcopy`:
|
| >>> import copy
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> c = copy.deepcopy(a)
| >>> c[2][0] = 10
| >>> c
| array([1, 'm', list([10, 3, 4])], dtype=object)
| >>> a
| array([1, 'm', list([2, 3, 4])], dtype=object)
|
| cumprod(...)
| a.cumprod(axis=None, dtype=None, out=None)
|
| Return the cumulative product of the elements along the given axis.
|
| Refer to `numpy.cumprod` for full documentation.
|
| See Also
| --------
| numpy.cumprod : equivalent function
|
| cumsum(...)
| a.cumsum(axis=None, dtype=None, out=None)
|
| Return the cumulative sum of the elements along the given axis.
|
| Refer to `numpy.cumsum` for full documentation.
|
| See Also
| --------
| numpy.cumsum : equivalent function
|
| diagonal(...)
| a.diagonal(offset=0, axis1=0, axis2=1)
|
| Return specified diagonals. In NumPy 1.9 the returned array is a
| read-only view instead of a copy as in previous NumPy versions. In
| a future version the read-only restriction will be removed.
|
| Refer to :func:`numpy.diagonal` for full documentation.
|
| See Also
| --------
| numpy.diagonal : equivalent function
|
| dot(...)
|
| dump(...)
| a.dump(file)
|
| Dump a pickle of the array to the specified file.
| The array can be read back with pickle.load or numpy.load.
|
| Parameters
| ----------
| file : str or Path
| A string naming the dump file.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| dumps(...)
| a.dumps()
|
| Returns the pickle of the array as a string.
| pickle.loads will convert the string back to an array.
|
| Parameters
| ----------
| None
|
| fill(...)
| a.fill(value)
|
| Fill the array with a scalar value.
|
| Parameters
| ----------
| value : scalar
| All elements of `a` will be assigned this value.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([1, 2])
| >>> a.fill(0)
| >>> a
| array([0, 0])
| >>> a = np.empty(2)
| >>> a.fill(1)
| >>> a
| array([1., 1.])
|
| Fill expects a scalar value and always behaves the same as assigning
| to a single array element. The following is a rare example where this
| distinction is important:
|
| >>> a = np.array([None, None], dtype=object)
| >>> a[0] = np.array(3)
| >>> a
| array([array(3), None], dtype=object)
| >>> a.fill(np.array(3))
| >>> a
| array([array(3), array(3)], dtype=object)
|
| Where other forms of assignments will unpack the array being assigned:
|
| >>> a[...] = np.array(3)
| >>> a
| array([3, 3], dtype=object)
|
| flatten(...)
| a.flatten(order='C')
|
| Return a copy of the array collapsed into one dimension.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| 'C' means to flatten in row-major (C-style) order.
| 'F' means to flatten in column-major (Fortran-
| style) order. 'A' means to flatten in column-major
| order if `a` is Fortran *contiguous* in memory,
| row-major order otherwise. 'K' means to flatten
| `a` in the order the elements occur in memory.
| The default is 'C'.
|
| Returns
| -------
| y : ndarray
| A copy of the input array, flattened to one dimension.
|
| See Also
| --------
| ravel : Return a flattened array.
| flat : A 1-D flat iterator over the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,2], [3,4]])
| >>> a.flatten()
| array([1, 2, 3, 4])
| >>> a.flatten('F')
| array([1, 3, 2, 4])
|
| getfield(...)
| a.getfield(dtype, offset=0)
|
| Returns a field of the given array as a certain type.
|
| A field is a view of the array data with a given data-type. The values in
| the view are determined by the given type and the offset into the current
| array in bytes. The offset needs to be such that the view dtype fits in the
| array dtype; for example an array of dtype complex128 has 16-byte elements.
| If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| between 0 and 12 bytes.
|
| Parameters
| ----------
| dtype : str or dtype
| The data type of the view. The dtype size of the view can not be larger
| than that of the array itself.
| offset : int
| Number of bytes to skip before beginning the element view.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.diag([1.+1.j]*2)
| >>> x[1, 1] = 2 + 4.j
| >>> x
| array([[1.+1.j, 0.+0.j],
| [0.+0.j, 2.+4.j]])
| >>> x.getfield(np.float64)
| array([[1., 0.],
| [0., 2.]])
|
| By choosing an offset of 8 bytes we can select the complex part of the
| array for our view:
|
| >>> x.getfield(np.float64, offset=8)
| array([[1., 0.],
| [0., 4.]])
|
| item(...)
| a.item(*args)
|
| Copy an element of an array to a standard Python scalar and return it.
|
| Parameters
| ----------
| \*args : Arguments (variable number and type)
|
| * none: in this case, the method only works for arrays
| with one element (`a.size == 1`), which element is
| copied into a standard Python scalar object and returned.
|
| * int_type: this argument is interpreted as a flat index into
| the array, specifying which element to copy and return.
|
| * tuple of int_types: functions as does a single int_type argument,
| except that the argument is interpreted as an nd-index into the
| array.
|
| Returns
| -------
| z : Standard Python scalar object
| A copy of the specified element of the array as a suitable
| Python scalar
|
| Notes
| -----
| When the data type of `a` is longdouble or clongdouble, item() returns
| a scalar array object because there is no available Python scalar that
| would not lose information. Void arrays return a buffer object for item(),
| unless fields are defined, in which case a tuple is returned.
|
| `item` is very similar to a[args], except, instead of an array scalar,
| a standard Python scalar is returned. This can be useful for speeding up
| access to elements of the array and doing arithmetic on elements of the
| array using Python's optimized math.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.random.seed(123)
| >>> x = np.random.randint(9, size=(3, 3))
| >>> x
| array([[2, 2, 6],
| [1, 3, 6],
| [1, 0, 1]])
| >>> x.item(3)
| 1
| >>> x.item(7)
| 0
| >>> x.item((0, 1))
| 2
| >>> x.item((2, 2))
| 1
|
| For an array with object dtype, elements are returned as-is.
|
| >>> a = np.array([np.int64(1)], dtype=object)
| >>> a.item() #return np.int64
| np.int64(1)
|
| max(...)
| a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the maximum along a given axis.
|
| Refer to `numpy.amax` for full documentation.
|
| See Also
| --------
| numpy.amax : equivalent function
|
| mean(...)
| a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
|
| Returns the average of the array elements along given axis.
|
| Refer to `numpy.mean` for full documentation.
|
| See Also
| --------
| numpy.mean : equivalent function
|
| min(...)
| a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the minimum along a given axis.
|
| Refer to `numpy.amin` for full documentation.
|
| See Also
| --------
| numpy.amin : equivalent function
|
| nonzero(...)
| a.nonzero()
|
| Return the indices of the elements that are non-zero.
|
| Refer to `numpy.nonzero` for full documentation.
|
| See Also
| --------
| numpy.nonzero : equivalent function
|
| prod(...)
| a.prod(axis=None, dtype=None, out=None, keepdims=False,
| initial=1, where=True)
|
| Return the product of the array elements over the given axis
|
| Refer to `numpy.prod` for full documentation.
|
| See Also
| --------
| numpy.prod : equivalent function
|
| put(...)
| a.put(indices, values, mode='raise')
|
| Set ``a.flat[n] = values[n]`` for all `n` in indices.
|
| Refer to `numpy.put` for full documentation.
|
| See Also
| --------
| numpy.put : equivalent function
|
| ravel(...)
| a.ravel([order])
|
| Return a flattened array.
|
| Refer to `numpy.ravel` for full documentation.
|
| See Also
| --------
| numpy.ravel : equivalent function
|
| ndarray.flat : a flat iterator on the array.
|
| repeat(...)
| a.repeat(repeats, axis=None)
|
| Repeat elements of an array.
|
| Refer to `numpy.repeat` for full documentation.
|
| See Also
| --------
| numpy.repeat : equivalent function
|
| reshape(...)
| a.reshape(shape, /, *, order='C', copy=None)
|
| Returns an array containing the same data with a new shape.
|
| Refer to `numpy.reshape` for full documentation.
|
| See Also
| --------
| numpy.reshape : equivalent function
|
| Notes
| -----
| Unlike the free function `numpy.reshape`, this method on `ndarray` allows
| the elements of the shape parameter to be passed in as separate arguments.
| For example, ``a.reshape(10, 11)`` is equivalent to
| ``a.reshape((10, 11))``.
|
| resize(...)
| a.resize(new_shape, refcheck=True)
|
| Change shape and size of array in-place.
|
| Parameters
| ----------
| new_shape : tuple of ints, or `n` ints
| Shape of resized array.
| refcheck : bool, optional
| If False, reference count will not be checked. Default is True.
|
| Returns
| -------
| None
|
| Raises
| ------
| ValueError
| If `a` does not own its own data or references or views to it exist,
| and the data memory must be changed.
| PyPy only: will always raise if the data memory must be changed, since
| there is no reliable way to determine if references or views to it
| exist.
|
| SystemError
| If the `order` keyword argument is specified. This behaviour is a
| bug in NumPy.
|
| See Also
| --------
| resize : Return a new array with the specified shape.
|
| Notes
| -----
| This reallocates space for the data area if necessary.
|
| Only contiguous arrays (data elements consecutive in memory) can be
| resized.
|
| The purpose of the reference count check is to make sure you
| do not use this array as a buffer for another Python object and then
| reallocate the memory. However, reference counts can increase in
| other ways so if you are sure that you have not shared the memory
| for this array with another Python object, then you may safely set
| `refcheck` to False.
|
| Examples
| --------
| Shrinking an array: array is flattened (in the order that the data are
| stored in memory), resized, and reshaped:
|
| >>> import numpy as np
|
| >>> a = np.array([[0, 1], [2, 3]], order='C')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [1]])
|
| >>> a = np.array([[0, 1], [2, 3]], order='F')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [2]])
|
| Enlarging an array: as above, but missing entries are filled with zeros:
|
| >>> b = np.array([[0, 1], [2, 3]])
| >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
| >>> b
| array([[0, 1, 2],
| [3, 0, 0]])
|
| Referencing an array prevents resizing...
|
| >>> c = a
| >>> a.resize((1, 1))
| Traceback (most recent call last):
| ...
| ValueError: cannot resize an array that references or is referenced ...
|
| Unless `refcheck` is False:
|
| >>> a.resize((1, 1), refcheck=False)
| >>> a
| array([[0]])
| >>> c
| array([[0]])
|
| round(...)
| a.round(decimals=0, out=None)
|
| Return `a` with each element rounded to the given number of decimals.
|
| Refer to `numpy.around` for full documentation.
|
| See Also
| --------
| numpy.around : equivalent function
|
| searchsorted(...)
| a.searchsorted(v, side='left', sorter=None)
|
| Find indices where elements of v should be inserted in a to maintain order.
|
| For full documentation, see `numpy.searchsorted`
|
| See Also
| --------
| numpy.searchsorted : equivalent function
|
| setfield(...)
| a.setfield(val, dtype, offset=0)
|
| Put a value into a specified place in a field defined by a data-type.
|
| Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| bytes into the field.
|
| Parameters
| ----------
| val : object
| Value to be placed in field.
| dtype : dtype object
| Data-type of the field in which to place `val`.
| offset : int, optional
| The number of bytes into the field at which to place `val`.
|
| Returns
| -------
| None
|
| See Also
| --------
| getfield
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.eye(3)
| >>> x.getfield(np.float64)
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
| >>> x.setfield(3, np.int32)
| >>> x.getfield(np.int32)
| array([[3, 3, 3],
| [3, 3, 3],
| [3, 3, 3]], dtype=int32)
| >>> x
| array([[1.0e+000, 1.5e-323, 1.5e-323],
| [1.5e-323, 1.0e+000, 1.5e-323],
| [1.5e-323, 1.5e-323, 1.0e+000]])
| >>> x.setfield(np.eye(3), np.int32)
| >>> x
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
|
| setflags(...)
| a.setflags(write=None, align=None, uic=None)
|
| Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| respectively.
|
| These Boolean-valued flags affect how numpy interprets the memory
| area used by `a` (see Notes below). The ALIGNED flag can only
| be set to True if the data is actually aligned according to the type.
| The WRITEBACKIFCOPY flag can never be set
| to True. The flag WRITEABLE can only be set to True if the array owns its
| own memory, or the ultimate owner of the memory exposes a writeable buffer
| interface, or is a string. (The exception for string is made so that
| unpickling can be done without copying memory.)
|
| Parameters
| ----------
| write : bool, optional
| Describes whether or not `a` can be written to.
| align : bool, optional
| Describes whether or not `a` is aligned properly for its type.
| uic : bool, optional
| Describes whether or not `a` is a copy of another "base" array.
|
| Notes
| -----
| Array flags provide information about how the memory area used
| for the array is to be interpreted. There are 7 Boolean flags
| in use, only three of which can be changed by the user:
| WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
|
| WRITEABLE (W) the data area can be written to;
|
| ALIGNED (A) the data and strides are aligned appropriately for the hardware
| (as determined by the compiler);
|
| WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| called, the base array will be updated with the contents of this array.
|
| All flags can be accessed using the single (upper case) letter as well
| as the full name.
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.array([[3, 1, 7],
| ... [2, 0, 0],
| ... [8, 5, 9]])
| >>> y
| array([[3, 1, 7],
| [2, 0, 0],
| [8, 5, 9]])
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
| >>> y.setflags(write=0, align=0)
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : False
| ALIGNED : False
| WRITEBACKIFCOPY : False
| >>> y.setflags(uic=1)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: cannot set WRITEBACKIFCOPY flag to True
|
| sort(...)
| a.sort(axis=-1, kind=None, order=None)
|
| Sort an array in-place. Refer to `numpy.sort` for full documentation.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
| and 'mergesort' use timsort under the covers and, in general, the
| actual implementation will vary with datatype. The 'mergesort' option
| is retained for backwards compatibility.
|
| .. versionchanged:: 1.15.0
| The 'stable' option was added.
|
| order : str 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, and 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.
|
| See Also
| --------
| numpy.sort : Return a sorted copy of an array.
| numpy.argsort : Indirect sort.
| numpy.lexsort : Indirect stable sort on multiple keys.
| numpy.searchsorted : Find elements in sorted array.
| numpy.partition: Partial sort.
|
| Notes
| -----
| See `numpy.sort` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,4], [3,1]])
| >>> a.sort(axis=1)
| >>> a
| array([[1, 4],
| [1, 3]])
| >>> a.sort(axis=0)
| >>> a
| array([[1, 3],
| [1, 4]])
|
| Use the `order` keyword to specify a field to use when sorting a
| structured array:
|
| >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
| >>> a.sort(order='y')
| >>> a
| array([(b'c', 1), (b'a', 2)],
| dtype=[('x', 'S1'), ('y', '<i8')])
|
| squeeze(...)
| a.squeeze(axis=None)
|
| Remove axes of length one from `a`.
|
| Refer to `numpy.squeeze` for full documentation.
|
| See Also
| --------
| numpy.squeeze : equivalent function
|
| std(...)
| a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the standard deviation of the array elements along given axis.
|
| Refer to `numpy.std` for full documentation.
|
| See Also
| --------
| numpy.std : equivalent function
|
| sum(...)
| a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
|
| Return the sum of the array elements over the given axis.
|
| Refer to `numpy.sum` for full documentation.
|
| See Also
| --------
| numpy.sum : equivalent function
|
| swapaxes(...)
| a.swapaxes(axis1, axis2)
|
| Return a view of the array with `axis1` and `axis2` interchanged.
|
| Refer to `numpy.swapaxes` for full documentation.
|
| See Also
| --------
| numpy.swapaxes : equivalent function
|
| take(...)
| a.take(indices, axis=None, out=None, mode='raise')
|
| Return an array formed from the elements of `a` at the given indices.
|
| Refer to `numpy.take` for full documentation.
|
| See Also
| --------
| numpy.take : equivalent function
|
| to_device(...)
|
| tobytes(...)
| a.tobytes(order='C')
|
| Construct Python bytes containing the raw data bytes in the array.
|
| Constructs Python bytes showing a copy of the raw contents of
| data memory. The bytes object is produced in C-order by default.
| This behavior is controlled by the ``order`` parameter.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| order : {'C', 'F', 'A'}, optional
| Controls the memory layout of the bytes object. 'C' means C-order,
| 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
| Fortran contiguous, 'C' otherwise. Default is 'C'.
|
| Returns
| -------
| s : bytes
| Python bytes exhibiting a copy of `a`'s raw data.
|
| See also
| --------
| frombuffer
| Inverse of this operation, construct a 1-dimensional array from Python
| bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
| >>> x.tobytes()
| b'\x00\x00\x01\x00\x02\x00\x03\x00'
| >>> x.tobytes('C') == x.tobytes()
| True
| >>> x.tobytes('F')
| b'\x00\x00\x02\x00\x01\x00\x03\x00'
|
| tofile(...)
| a.tofile(fid, sep="", format="%s")
|
| Write array to a file as text or binary (default).
|
| Data is always written in 'C' order, independent of the order of `a`.
| The data produced by this method can be recovered using the function
| fromfile().
|
| Parameters
| ----------
| fid : file or str or Path
| An open file object, or a string containing a filename.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| sep : str
| Separator between array items for text output.
| If "" (empty), a binary file is written, equivalent to
| ``file.write(a.tobytes())``.
| format : str
| Format string for text file output.
| Each entry in the array is formatted to text by first converting
| it to the closest Python type, and then using "format" % item.
|
| Notes
| -----
| This is a convenience function for quick storage of array data.
| Information on endianness and precision is lost, so this method is not a
| good choice for files intended to archive data or transport data between
| machines with different endianness. Some of these problems can be overcome
| by outputting the data as text files, at the expense of speed and file
| size.
|
| When fid is a file object, array contents are directly written to the
| file, bypassing the file object's ``write`` method. As a result, tofile
| cannot be used with files objects supporting compression (e.g., GzipFile)
| or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
|
| tolist(...)
| a.tolist()
|
| Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
|
| Return a copy of the array data as a (nested) Python list.
| Data items are converted to the nearest compatible builtin Python type, via
| the `~numpy.ndarray.item` function.
|
| If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
| not be a list at all, but a simple Python scalar.
|
| Parameters
| ----------
| none
|
| Returns
| -------
| y : object, or list of object, or list of list of object, or ...
| The possibly nested list of array elements.
|
| Notes
| -----
| The array may be recreated via ``a = np.array(a.tolist())``, although this
| may sometimes lose precision.
|
| Examples
| --------
| For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
| except that ``tolist`` changes numpy scalars to Python scalars:
|
| >>> import numpy as np
| >>> a = np.uint32([1, 2])
| >>> a_list = list(a)
| >>> a_list
| [1, 2]
| >>> type(a_list[0])
| <class 'numpy.uint32'>
| >>> a_tolist = a.tolist()
| >>> a_tolist
| [1, 2]
| >>> type(a_tolist[0])
| <class 'int'>
|
| Additionally, for a 2D array, ``tolist`` applies recursively:
|
| >>> a = np.array([[1, 2], [3, 4]])
| >>> list(a)
| [array([1, 2]), array([3, 4])]
| >>> a.tolist()
| [[1, 2], [3, 4]]
|
| The base case for this recursion is a 0D array:
|
| >>> a = np.array(1)
| >>> list(a)
| Traceback (most recent call last):
| ...
| TypeError: iteration over a 0-d array
| >>> a.tolist()
| 1
|
| tostring(...)
| a.tostring(order='C')
|
| A compatibility alias for `~ndarray.tobytes`, with exactly the same
| behavior.
|
| Despite its name, it returns :class:`bytes` not :class:`str`\ s.
|
| .. deprecated:: 1.19.0
|
| trace(...)
| a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
|
| Return the sum along diagonals of the array.
|
| Refer to `numpy.trace` for full documentation.
|
| See Also
| --------
| numpy.trace : equivalent function
|
| transpose(...)
| a.transpose(*axes)
|
| Returns a view of the array with axes transposed.
|
| Refer to `numpy.transpose` for full documentation.
|
| Parameters
| ----------
| axes : None, tuple of ints, or `n` ints
|
| * None or no argument: reverses the order of the axes.
|
| * tuple of ints: `i` in the `j`-th place in the tuple means that the
| array's `i`-th axis becomes the transposed array's `j`-th axis.
|
| * `n` ints: same as an n-tuple of the same ints (this form is
| intended simply as a "convenience" alternative to the tuple form).
|
| Returns
| -------
| p : ndarray
| View of the array with its axes suitably permuted.
|
| See Also
| --------
| transpose : Equivalent function.
| ndarray.T : Array property returning the array transposed.
| ndarray.reshape : Give a new shape to an array without changing its data.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.transpose()
| array([[1, 3],
| [2, 4]])
| >>> a.transpose((1, 0))
| array([[1, 3],
| [2, 4]])
| >>> a.transpose(1, 0)
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.transpose()
| array([1, 2, 3, 4])
|
| var(...)
| a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the variance of the array elements, along given axis.
|
| Refer to `numpy.var` for full documentation.
|
| See Also
| --------
| numpy.var : equivalent function
|
| view(...)
| a.view([dtype][, type])
|
| New view of array with the same data.
|
| .. note::
| Passing None for ``dtype`` is different from omitting the parameter,
| since the former invokes ``dtype(None)`` which is an alias for
| ``dtype('float64')``.
|
| Parameters
| ----------
| dtype : data-type or ndarray sub-class, optional
| Data-type descriptor of the returned view, e.g., float32 or int16.
| Omitting it results in the view having the same data-type as `a`.
| This argument can also be specified as an ndarray sub-class, which
| then specifies the type of the returned object (this is equivalent to
| setting the ``type`` parameter).
| type : Python type, optional
| Type of the returned view, e.g., ndarray or matrix. Again, omission
| of the parameter results in type preservation.
|
| Notes
| -----
| ``a.view()`` is used two different ways:
|
| ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| of the array's memory with a different data-type. This can cause a
| reinterpretation of the bytes of memory.
|
| ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| returns an instance of `ndarray_subclass` that looks at the same array
| (same shape, dtype, etc.) This does not cause a reinterpretation of the
| memory.
|
| For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| bytes per entry than the previous dtype (for example, converting a regular
| array to a structured array), then the last axis of ``a`` must be
| contiguous. This axis will be resized in the result.
|
| .. versionchanged:: 1.23.0
| Only the last axis needs to be contiguous. Previously, the entire array
| had to be C-contiguous.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
|
| Viewing array data using a different type and dtype:
|
| >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
| >>> y = x.view(dtype=nonneg, type=np.recarray)
| >>> x["a"]
| array([-1], dtype=int8)
| >>> y.a
| array([255], dtype=uint8)
|
| Creating a view on a structured array so it can be used in calculations
|
| >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
| >>> xv = x.view(dtype=np.int8).reshape(-1,2)
| >>> xv
| array([[1, 2],
| [3, 4]], dtype=int8)
| >>> xv.mean(0)
| array([2., 3.])
|
| Making changes to the view changes the underlying array
|
| >>> xv[0,1] = 20
| >>> x
| array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
|
| Using a view to convert an array to a recarray:
|
| >>> z = x.view(np.recarray)
| >>> z.a
| array([1, 3], dtype=int8)
|
| Views share data:
|
| >>> x[0] = (9, 10)
| >>> z[0]
| np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
|
| Views that change the dtype size (bytes per entry) should normally be
| avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
|
| >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
| >>> y = x[:, ::2]
| >>> y
| array([[1, 3],
| [4, 6]], dtype=int16)
| >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
| Traceback (most recent call last):
| ...
| ValueError: To change to a dtype of a different size, the last axis must be contiguous
| >>> z = y.copy()
| >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
| array([[(1, 3)],
| [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
|
| However, views that change dtype are totally fine for arrays with a
| contiguous last axis, even if the rest of the axes are not C-contiguous:
|
| >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
| >>> x.transpose(1, 0, 2).view(np.int16)
| array([[[ 256, 770],
| [3340, 3854]],
| <BLANKLINE>
| [[1284, 1798],
| [4368, 4882]],
| <BLANKLINE>
| [[2312, 2826],
| [5396, 5910]]], dtype=int16)
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.ndarray:
|
| __class_getitem__(...)
| a.__class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.ndarray` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.ndarray` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.ndarray[Any, np.dtype[Any]]
| numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
| numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.ndarray:
|
| T
| View of the transposed array.
|
| Same as ``self.transpose()``.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.T
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.T
| array([1, 2, 3, 4])
|
| See Also
| --------
| transpose
|
| __array_interface__
| Array protocol: Python side.
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: C-struct side.
|
| base
| Base object if memory is from some other object.
|
| Examples
| --------
| The base of an array that owns its memory is None:
|
| >>> import numpy as np
| >>> x = np.array([1,2,3,4])
| >>> x.base is None
| True
|
| Slicing creates a view, whose memory is shared with x:
|
| >>> y = x[2:]
| >>> y.base is x
| True
|
| ctypes
| An object to simplify the interaction of the array with the ctypes
| module.
|
| This attribute creates an object that makes it easier to use arrays
| when calling shared libraries with the ctypes module. The returned
| object has, among others, data, shape, and strides attributes (see
| Notes below) which themselves return ctypes objects that can be used
| as arguments to a shared library.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| c : Python object
| Possessing attributes data, shape, strides, etc.
|
| See Also
| --------
| numpy.ctypeslib
|
| Notes
| -----
| Below are the public attributes of this object which were documented
| in "Guide to NumPy" (we have omitted undocumented public attributes,
| as well as documented private attributes):
|
| .. autoattribute:: numpy._core._internal._ctypes.data
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.shape
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.strides
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.data_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.shape_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.strides_as
| :noindex:
|
| If the ctypes module is not available, then the ctypes attribute
| of array objects still returns something useful, but ctypes objects
| are not returned and errors may be raised instead. In particular,
| the object will still have the ``as_parameter`` attribute which will
| return an integer equal to the data attribute.
|
| Examples
| --------
| >>> import numpy as np
| >>> import ctypes
| >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| >>> x
| array([[0, 1],
| [2, 3]], dtype=int32)
| >>> x.ctypes.data
| 31962608 # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| c_uint(0)
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| c_ulong(4294967296)
| >>> x.ctypes.shape
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| >>> x.ctypes.strides
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
|
| data
| Python buffer object pointing to the start of the array's data.
|
| device
|
| dtype
| Data-type of the array's elements.
|
| .. warning::
|
| Setting ``arr.dtype`` is discouraged and may be deprecated in the
| future. Setting will replace the ``dtype`` without modifying the
| memory (see also `ndarray.view` and `ndarray.astype`).
|
| Parameters
| ----------
| None
|
| Returns
| -------
| d : numpy dtype object
|
| See Also
| --------
| ndarray.astype : Cast the values contained in the array to a new data-type.
| ndarray.view : Create a view of the same data but a different data-type.
| numpy.dtype
|
| Examples
| --------
| >>> x
| array([[0, 1],
| [2, 3]])
| >>> x.dtype
| dtype('int32')
| >>> type(x.dtype)
| <type 'numpy.dtype'>
|
| flags
| Information about the memory layout of the array.
|
| Attributes
| ----------
| C_CONTIGUOUS (C)
| The data is in a single, C-style contiguous segment.
| F_CONTIGUOUS (F)
| The data is in a single, Fortran-style contiguous segment.
| OWNDATA (O)
| The array owns the memory it uses or borrows it from another object.
| WRITEABLE (W)
| The data area can be written to. Setting this to False locks
| the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| from its base array at creation time, but a view of a writeable
| array may be subsequently locked while the base array remains writeable.
| (The opposite is not true, in that a view of a locked array may not
| be made writeable. However, currently, locking a base object does not
| lock any views that already reference it, so under that circumstance it
| is possible to alter the contents of a locked array via a previously
| created writeable view onto it.) Attempting to change a non-writeable
| array raises a RuntimeError exception.
| ALIGNED (A)
| The data and all elements are aligned appropriately for the hardware.
| WRITEBACKIFCOPY (X)
| This array is a copy of some other array. The C-API function
| PyArray_ResolveWritebackIfCopy must be called before deallocating
| to the base array will be updated with the contents of this array.
| FNC
| F_CONTIGUOUS and not C_CONTIGUOUS.
| FORC
| F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| BEHAVED (B)
| ALIGNED and WRITEABLE.
| CARRAY (CA)
| BEHAVED and C_CONTIGUOUS.
| FARRAY (FA)
| BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
|
| Notes
| -----
| The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| names are only supported in dictionary access.
|
| Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| changed by the user, via direct assignment to the attribute or dictionary
| entry, or by calling `ndarray.setflags`.
|
| The array flags cannot be set arbitrarily:
|
| - WRITEBACKIFCOPY can only be set ``False``.
| - ALIGNED can only be set ``True`` if the data is truly aligned.
| - WRITEABLE can only be set ``True`` if the array owns its own memory
| or the ultimate owner of the memory exposes a writeable buffer
| interface or is a string.
|
| Arrays can be both C-style and Fortran-style contiguous simultaneously.
| This is clear for 1-dimensional arrays, but can also be true for higher
| dimensional arrays.
|
| Even for contiguous arrays a stride for a given dimension
| ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| or the array has no elements.
| It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| Fortran-style contiguous arrays is true.
|
| flat
| A 1-D iterator over the array.
|
| This is a `numpy.flatiter` instance, which acts similarly to, but is not
| a subclass of, Python's built-in iterator object.
|
| See Also
| --------
| flatten : Return a copy of the array collapsed into one dimension.
|
| flatiter
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(1, 7).reshape(2, 3)
| >>> x
| array([[1, 2, 3],
| [4, 5, 6]])
| >>> x.flat[3]
| 4
| >>> x.T
| array([[1, 4],
| [2, 5],
| [3, 6]])
| >>> x.T.flat[3]
| 5
| >>> type(x.flat)
| <class 'numpy.flatiter'>
|
| An assignment example:
|
| >>> x.flat = 3; x
| array([[3, 3, 3],
| [3, 3, 3]])
| >>> x.flat[[1,4]] = 1; x
| array([[3, 1, 3],
| [3, 1, 3]])
|
| imag
| The imaginary part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.imag
| array([ 0. , 0.70710678])
| >>> x.imag.dtype
| dtype('float64')
|
| itemset
|
| itemsize
| Length of one array element in bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1,2,3], dtype=np.float64)
| >>> x.itemsize
| 8
| >>> x = np.array([1,2,3], dtype=np.complex128)
| >>> x.itemsize
| 16
|
| mT
| View of the matrix transposed array.
|
| The matrix transpose is the transpose of the last two dimensions, even
| if the array is of higher dimension.
|
| .. versionadded:: 2.0
|
| Raises
| ------
| ValueError
| If the array is of dimension less than 2.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.mT
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.arange(8).reshape((2, 2, 2))
| >>> a
| array([[[0, 1],
| [2, 3]],
| <BLANKLINE>
| [[4, 5],
| [6, 7]]])
| >>> a.mT
| array([[[0, 2],
| [1, 3]],
| <BLANKLINE>
| [[4, 6],
| [5, 7]]])
|
| nbytes
| Total bytes consumed by the elements of the array.
|
| Notes
| -----
| Does not include memory consumed by non-element attributes of the
| array object.
|
| See Also
| --------
| sys.getsizeof
| Memory consumed by the object itself without parents in case view.
| This does include memory consumed by non-element attributes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3,5,2), dtype=np.complex128)
| >>> x.nbytes
| 480
| >>> np.prod(x.shape) * x.itemsize
| 480
|
| ndim
| Number of array dimensions.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3])
| >>> x.ndim
| 1
| >>> y = np.zeros((2, 3, 4))
| >>> y.ndim
| 3
|
| newbyteorder
|
| ptp
|
| real
| The real part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.real
| array([ 1. , 0.70710678])
| >>> x.real.dtype
| dtype('float64')
|
| See Also
| --------
| numpy.real : equivalent function
|
| shape
| Tuple of array dimensions.
|
| The shape property is usually used to get the current shape of an array,
| but may also be used to reshape the array in-place by assigning a tuple of
| array dimensions to it. As with `numpy.reshape`, one of the new shape
| dimensions can be -1, in which case its value is inferred from the size of
| the array and the remaining dimensions. Reshaping an array in-place will
| fail if a copy is required.
|
| .. warning::
|
| Setting ``arr.shape`` is discouraged and may be deprecated in the
| future. Using `ndarray.reshape` is the preferred approach.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3, 4])
| >>> x.shape
| (4,)
| >>> y = np.zeros((2, 3, 4))
| >>> y.shape
| (2, 3, 4)
| >>> y.shape = (3, 8)
| >>> y
| array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| >>> y.shape = (3, 6)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: total size of new array must be unchanged
| >>> np.zeros((4,2))[::2].shape = (-1,)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| AttributeError: Incompatible shape for in-place modification. Use
| `.reshape()` to make a copy with the desired shape.
|
| See Also
| --------
| numpy.shape : Equivalent getter function.
| numpy.reshape : Function similar to setting ``shape``.
| ndarray.reshape : Method similar to setting ``shape``.
|
| size
| Number of elements in the array.
|
| Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| dimensions.
|
| Notes
| -----
| `a.size` returns a standard arbitrary precision Python integer. This
| may not be the case with other methods of obtaining the same value
| (like the suggested ``np.prod(a.shape)``, which returns an instance
| of ``np.int_``), and may be relevant if the value is used further in
| calculations that may overflow a fixed size integer type.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| >>> x.size
| 30
| >>> np.prod(x.shape)
| 30
|
| strides
| Tuple of bytes to step in each dimension when traversing an array.
|
| The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| is::
|
| offset = sum(np.array(i) * a.strides)
|
| A more detailed explanation of strides can be found in
| :ref:`arrays.ndarray`.
|
| .. warning::
|
| Setting ``arr.strides`` is discouraged and may be deprecated in the
| future. `numpy.lib.stride_tricks.as_strided` should be preferred
| to create a new view of the same data in a safer way.
|
| Notes
| -----
| Imagine an array of 32-bit integers (each 4 bytes)::
|
| x = np.array([[0, 1, 2, 3, 4],
| [5, 6, 7, 8, 9]], dtype=np.int32)
|
| This array is stored in memory as 40 bytes, one after the other
| (known as a contiguous block of memory). The strides of an array tell
| us how many bytes we have to skip in memory to move to the next position
| along a certain axis. For example, we have to skip 4 bytes (1 value) to
| move to the next column, but 20 bytes (5 values) to get to the same
| position in the next row. As such, the strides for the array `x` will be
| ``(20, 4)``.
|
| See Also
| --------
| numpy.lib.stride_tricks.as_strided
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| >>> y
| array([[[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]],
| [[12, 13, 14, 15],
| [16, 17, 18, 19],
| [20, 21, 22, 23]]])
| >>> y.strides
| (48, 16, 4)
| >>> y[1,1,1]
| 17
| >>> offset=sum(y.strides * np.array((1,1,1)))
| >>> offset/y.itemsize
| 17
|
| >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| >>> x.strides
| (32, 4, 224, 1344)
| >>> i = np.array([3,5,2,2])
| >>> offset = sum(i * x.strides)
| >>> x[3,5,2,2]
| 813
| >>> offset / x.itemsize
| 813
FUNCTIONS
array(obj, itemsize=None, copy=True, unicode=None, order=None)
Create a `~numpy.char.chararray`.
.. note::
This class is provided for numarray backward-compatibility.
New code (not concerned with numarray compatibility) should use
arrays of type `bytes_` or `str_` and use the free functions
in :mod:`numpy.char` for fast vectorized string operations instead.
Versus a NumPy array of dtype `bytes_` or `str_`, this
class adds the following functionality:
1) values automatically have whitespace removed from the end
when indexed
2) comparison operators automatically remove whitespace from the
end when comparing values
3) vectorized string operations are provided as methods
(e.g. `chararray.endswith <numpy.char.chararray.endswith>`)
and infix operators (e.g. ``+, *, %``)
Parameters
----------
obj : array of str or unicode-like
itemsize : int, optional
`itemsize` is the number of characters per scalar in the
resulting array. If `itemsize` is None, and `obj` is an
object array or a Python list, the `itemsize` will be
automatically determined. If `itemsize` is provided and `obj`
is of type str or unicode, then the `obj` string will be
chunked into `itemsize` pieces.
copy : bool, optional
If true (default), then the object is copied. Otherwise, a copy
will only be made if ``__array__`` returns a copy, if obj is a
nested sequence, or if a copy is needed to satisfy any of the other
requirements (`itemsize`, unicode, `order`, etc.).
unicode : bool, optional
When true, the resulting `~numpy.char.chararray` can contain Unicode
characters, when false only 8-bit characters. If unicode is
None and `obj` is one of the following:
- a `~numpy.char.chararray`,
- an ndarray of type :class:`str_` or :class:`bytes_`
- a Python :class:`str` or :class:`bytes` object,
then the unicode setting of the output array will be
automatically determined.
order : {'C', 'F', 'A'}, optional
Specify the order of the array. If order is 'C' (default), then the
array will be in C-contiguous order (last-index varies the
fastest). If order is 'F', then the returned array
will be in Fortran-contiguous order (first-index varies the
fastest). If order is 'A', then the returned array may
be in any order (either C-, Fortran-contiguous, or even
discontiguous).
asarray(obj, itemsize=None, unicode=None, order=None)
Convert the input to a `~numpy.char.chararray`, copying the data only if
necessary.
Versus a NumPy array of dtype `bytes_` or `str_`, this
class adds the following functionality:
1) values automatically have whitespace removed from the end
when indexed
2) comparison operators automatically remove whitespace from the
end when comparing values
3) vectorized string operations are provided as methods
(e.g. `chararray.endswith <numpy.char.chararray.endswith>`)
and infix operators (e.g. ``+``, ``*``, ``%``)
Parameters
----------
obj : array of str or unicode-like
itemsize : int, optional
`itemsize` is the number of characters per scalar in the
resulting array. If `itemsize` is None, and `obj` is an
object array or a Python list, the `itemsize` will be
automatically determined. If `itemsize` is provided and `obj`
is of type str or unicode, then the `obj` string will be
chunked into `itemsize` pieces.
unicode : bool, optional
When true, the resulting `~numpy.char.chararray` can contain Unicode
characters, when false only 8-bit characters. If unicode is
None and `obj` is one of the following:
- a `~numpy.char.chararray`,
- an ndarray of type `str_` or `unicode_`
- a Python str or unicode object,
then the unicode setting of the output array will be
automatically determined.
order : {'C', 'F'}, optional
Specify the order of the array. If order is 'C' (default), then the
array will be in C-contiguous order (last-index varies the
fastest). If order is 'F', then the returned array
will be in Fortran-contiguous order (first-index varies the
fastest).
Examples
--------
>>> import numpy as np
>>> np.char.asarray(['hello', 'world'])
chararray(['hello', 'world'], dtype='<U5')
capitalize(a)
Return a copy of ``a`` with only the first character of each element
capitalized.
Calls :meth:`str.capitalize` element-wise.
For byte strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array of strings to capitalize.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.capitalize
Examples
--------
>>> import numpy as np
>>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c
array(['a1b2', '1b2a', 'b2a1', '2a1b'],
dtype='|S4')
>>> np.strings.capitalize(c)
array(['A1b2', '1b2a', 'B2a1', '2a1b'],
dtype='|S4')
center(a, width, fillchar=' ')
Return a copy of `a` with its elements centered in a string of
length `width`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
width : array_like, with any integer dtype
The length of the resulting strings, unless ``width < str_len(a)``.
fillchar : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Optional padding character to use (default is space).
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.center
Notes
-----
While it is possible for ``a`` and ``fillchar`` to have different dtypes,
passing a non-ASCII character in ``fillchar`` when ``a`` is of dtype "S"
is not allowed, and a ``ValueError`` is raised.
Examples
--------
>>> import numpy as np
>>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c
array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4')
>>> np.strings.center(c, width=9)
array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='<U9')
>>> np.strings.center(c, width=9, fillchar='*')
array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='<U9')
>>> np.strings.center(c, width=1)
array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4')
compare_chararrays(...)
compare_chararrays(a1, a2, cmp, rstrip)
Performs element-wise comparison of two string arrays using the
comparison operator specified by `cmp`.
Parameters
----------
a1, a2 : array_like
Arrays to be compared.
cmp : {"<", "<=", "==", ">=", ">", "!="}
Type of comparison.
rstrip : Boolean
If True, the spaces at the end of Strings are removed before the comparison.
Returns
-------
out : ndarray
The output array of type Boolean with the same shape as a and b.
Raises
------
ValueError
If `cmp` is not valid.
TypeError
If at least one of `a` or `b` is a non-string array
Examples
--------
>>> import numpy as np
>>> a = np.array(["a", "b", "cde"])
>>> b = np.array(["a", "a", "dec"])
>>> np.char.compare_chararrays(a, b, ">", True)
array([False, True, False])
count(a, sub, start=0, end=None)
Returns an array with the number of non-overlapping occurrences of
substring ``sub`` in the range [``start``, ``end``).
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
The substring to search for.
start, end : array_like, with any integer dtype
The range to look in, interpreted as in slice notation.
Returns
-------
y : ndarray
Output array of ints
See Also
--------
str.count
Examples
--------
>>> import numpy as np
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.count(c, 'A')
array([3, 1, 1])
>>> np.strings.count(c, 'aA')
array([3, 1, 0])
>>> np.strings.count(c, 'A', start=1, end=4)
array([2, 1, 1])
>>> np.strings.count(c, 'A', start=1, end=3)
array([1, 0, 0])
decode(a, encoding=None, errors=None)
Calls :meth:`bytes.decode` element-wise.
The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the
:mod:`codecs` module.
Parameters
----------
a : array_like, with ``bytes_`` dtype
encoding : str, optional
The name of an encoding
errors : str, optional
Specifies how to handle encoding errors
Returns
-------
out : ndarray
See Also
--------
:py:meth:`bytes.decode`
Notes
-----
The type of the result will depend on the encoding specified.
Examples
--------
>>> import numpy as np
>>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
... b'\x81\x82\xc2\xc1\xc2\x82\x81'])
>>> c
array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
>>> np.strings.decode(c, encoding='cp037')
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
encode(a, encoding=None, errors=None)
Calls :meth:`str.encode` element-wise.
The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the
:mod:`codecs` module.
Parameters
----------
a : array_like, with ``StringDType`` or ``str_`` dtype
encoding : str, optional
The name of an encoding
errors : str, optional
Specifies how to handle encoding errors
Returns
-------
out : ndarray
See Also
--------
str.encode
Notes
-----
The type of the result will depend on the encoding specified.
Examples
--------
>>> import numpy as np
>>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.strings.encode(a, encoding='cp037')
array([b'ÁÁÁ', b'@@Á@@',
b'ÂÁÂ'], dtype='|S7')
endswith(a, suffix, start=0, end=None)
Returns a boolean array which is `True` where the string element
in ``a`` ends with ``suffix``, otherwise `False`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
suffix : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
start, end : array_like, with any integer dtype
With ``start``, test beginning at that position. With ``end``,
stop comparing at that position.
Returns
-------
out : ndarray
Output array of bools
See Also
--------
str.endswith
Examples
--------
>>> import numpy as np
>>> s = np.array(['foo', 'bar'])
>>> s
array(['foo', 'bar'], dtype='<U3')
>>> np.strings.endswith(s, 'ar')
array([False, True])
>>> np.strings.endswith(s, 'a', start=1, end=2)
array([False, True])
equal(x1, x2)
Return (x1 == x2) element-wise.
Unlike `numpy.equal`, this comparison is performed by first
stripping whitespace characters from the end of the string. This
behavior is provided for backward-compatibility with numarray.
Parameters
----------
x1, x2 : array_like of str or unicode
Input arrays of the same shape.
Returns
-------
out : ndarray
Output array of bools.
Examples
--------
>>> import numpy as np
>>> y = "aa "
>>> x = "aa"
>>> np.char.equal(x, y)
array(True)
See Also
--------
not_equal, greater_equal, less_equal, greater, less
expandtabs(a, tabsize=8)
Return a copy of each string element where all tab characters are
replaced by one or more spaces.
Calls :meth:`str.expandtabs` element-wise.
Return a copy of each string element where all tab characters are
replaced by one or more spaces, depending on the current column
and the given `tabsize`. The column number is reset to zero after
each newline occurring in the string. This doesn't understand other
non-printing characters or escape sequences.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array
tabsize : int, optional
Replace tabs with `tabsize` number of spaces. If not given defaults
to 8 spaces.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input type
See Also
--------
str.expandtabs
Examples
--------
>>> import numpy as np
>>> a = np.array([' Hello world'])
>>> np.strings.expandtabs(a, tabsize=4) # doctest: +SKIP
array([' Hello world'], dtype='<U21') # doctest: +SKIP
find(a, sub, start=0, end=None)
For each element, return the lowest index in the string where
substring ``sub`` is found, such that ``sub`` is contained in the
range [``start``, ``end``).
Parameters
----------
a : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
sub : array_like, with `np.bytes_` or `np.str_` dtype
The substring to search for.
start, end : array_like, with any integer dtype
The range to look in, interpreted as in slice notation.
Returns
-------
y : ndarray
Output array of ints
See Also
--------
str.find
Examples
--------
>>> import numpy as np
>>> a = np.array(["NumPy is a Python library"])
>>> np.strings.find(a, "Python")
array([11])
greater(x1, x2)
Return (x1 > x2) element-wise.
Unlike `numpy.greater`, this comparison is performed by first
stripping whitespace characters from the end of the string. This
behavior is provided for backward-compatibility with numarray.
Parameters
----------
x1, x2 : array_like of str or unicode
Input arrays of the same shape.
Returns
-------
out : ndarray
Output array of bools.
See Also
--------
equal, not_equal, greater_equal, less_equal, less
Examples
--------
>>> import numpy as np
>>> x1 = np.array(['a', 'b', 'c'])
>>> np.char.greater(x1, 'b')
array([False, False, True])
greater_equal(x1, x2)
Return (x1 >= x2) element-wise.
Unlike `numpy.greater_equal`, this comparison is performed by
first stripping whitespace characters from the end of the string.
This behavior is provided for backward-compatibility with
numarray.
Parameters
----------
x1, x2 : array_like of str or unicode
Input arrays of the same shape.
Returns
-------
out : ndarray
Output array of bools.
See Also
--------
equal, not_equal, less_equal, greater, less
Examples
--------
>>> import numpy as np
>>> x1 = np.array(['a', 'b', 'c'])
>>> np.char.greater_equal(x1, 'b')
array([False, True, True])
index(a, sub, start=0, end=None)
Like `find`, but raises :exc:`ValueError` when the substring is not found.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
start, end : array_like, with any integer dtype, optional
Returns
-------
out : ndarray
Output array of ints.
See Also
--------
find, str.index
Examples
--------
>>> import numpy as np
>>> a = np.array(["Computer Science"])
>>> np.strings.index(a, "Science", start=0, end=None)
array([9])
join = _join(sep, seq)
Return a string which is the concatenation of the strings in the
sequence `seq`.
Calls :meth:`str.join` element-wise.
Parameters
----------
sep : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
seq : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.join
Examples
--------
>>> import numpy as np
>>> np.strings.join('-', 'osd') # doctest: +SKIP
array('o-s-d', dtype='<U5') # doctest: +SKIP
>>> np.strings.join(['-', '.'], ['ghc', 'osd']) # doctest: +SKIP
array(['g-h-c', 'o.s.d'], dtype='<U5') # doctest: +SKIP
less(x1, x2)
Return (x1 < x2) element-wise.
Unlike `numpy.greater`, this comparison is performed by first
stripping whitespace characters from the end of the string. This
behavior is provided for backward-compatibility with numarray.
Parameters
----------
x1, x2 : array_like of str or unicode
Input arrays of the same shape.
Returns
-------
out : ndarray
Output array of bools.
See Also
--------
equal, not_equal, greater_equal, less_equal, greater
Examples
--------
>>> import numpy as np
>>> x1 = np.array(['a', 'b', 'c'])
>>> np.char.less(x1, 'b')
array([True, False, False])
less_equal(x1, x2)
Return (x1 <= x2) element-wise.
Unlike `numpy.less_equal`, this comparison is performed by first
stripping whitespace characters from the end of the string. This
behavior is provided for backward-compatibility with numarray.
Parameters
----------
x1, x2 : array_like of str or unicode
Input arrays of the same shape.
Returns
-------
out : ndarray
Output array of bools.
See Also
--------
equal, not_equal, greater_equal, greater, less
Examples
--------
>>> import numpy as np
>>> x1 = np.array(['a', 'b', 'c'])
>>> np.char.less_equal(x1, 'b')
array([ True, True, False])
ljust(a, width, fillchar=' ')
Return an array with the elements of `a` left-justified in a
string of length `width`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
width : array_like, with any integer dtype
The length of the resulting strings, unless ``width < str_len(a)``.
fillchar : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Optional character to use for padding (default is space).
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.ljust
Notes
-----
While it is possible for ``a`` and ``fillchar`` to have different dtypes,
passing a non-ASCII character in ``fillchar`` when ``a`` is of dtype "S"
is not allowed, and a ``ValueError`` is raised.
Examples
--------
>>> import numpy as np
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.strings.ljust(c, width=3)
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.ljust(c, width=9)
array(['aAaAaA ', ' aA ', 'abBABba '], dtype='<U9')
lower(a)
Return an array with the elements converted to lowercase.
Call :meth:`str.lower` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.lower
Examples
--------
>>> import numpy as np
>>> c = np.array(['A1B C', '1BCA', 'BCA1']); c
array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
>>> np.strings.lower(c)
array(['a1b c', '1bca', 'bca1'], dtype='<U5')
lstrip(a, chars=None)
For each element in `a`, return a copy with the leading characters
removed.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
chars : scalar with the same dtype as ``a``, optional
The ``chars`` argument is a string specifying the set of
characters to be removed. If ``None``, the ``chars``
argument defaults to removing whitespace. The ``chars`` argument
is not a prefix or suffix; rather, all combinations of its
values are stripped.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.lstrip
Examples
--------
>>> import numpy as np
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
# The 'a' variable is unstripped from c[1] because of leading whitespace.
>>> np.strings.lstrip(c, 'a')
array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7')
>>> np.strings.lstrip(c, 'A') # leaves c unchanged
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> (np.strings.lstrip(c, ' ') == np.strings.lstrip(c, '')).all()
np.False_
>>> (np.strings.lstrip(c, ' ') == np.strings.lstrip(c)).all()
np.True_
mod(a, values)
Return (a % i), that is pre-Python 2.6 string formatting
(interpolation), element-wise for a pair of array_likes of str
or unicode.
Parameters
----------
a : array_like, with `np.bytes_` or `np.str_` dtype
values : array_like of values
These values will be element-wise interpolated into the string.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
Examples
--------
>>> import numpy as np
>>> a = np.array(["NumPy is a %s library"])
>>> np.strings.mod(a, values=["Python"])
array(['NumPy is a Python library'], dtype='<U25')
>>> a = np.array([b'%d bytes', b'%d bits'])
>>> values = np.array([8, 64])
>>> np.strings.mod(a, values)
array([b'8 bytes', b'64 bits'], dtype='|S7')
multiply(a, i)
Return (a * i), that is string multiple concatenation,
element-wise.
Values in ``i`` of less than 0 are treated as 0 (which yields an
empty string).
Parameters
----------
a : array_like, with `np.bytes_` or `np.str_` dtype
i : array_like, with any integer dtype
Returns
-------
out : ndarray
Output array of str or unicode, depending on input types
Notes
-----
This is a thin wrapper around np.strings.multiply that raises
`ValueError` when ``i`` is not an integer. It only
exists for backwards-compatibility.
Examples
--------
>>> import numpy as np
>>> a = np.array(["a", "b", "c"])
>>> np.strings.multiply(a, 3)
array(['aaa', 'bbb', 'ccc'], dtype='<U3')
>>> i = np.array([1, 2, 3])
>>> np.strings.multiply(a, i)
array(['a', 'bb', 'ccc'], dtype='<U3')
>>> np.strings.multiply(np.array(['a']), i)
array(['a', 'aa', 'aaa'], dtype='<U3')
>>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
>>> np.strings.multiply(a, 3)
array([['aaa', 'bbb', 'ccc'],
['ddd', 'eee', 'fff']], dtype='<U3')
>>> np.strings.multiply(a, i)
array([['a', 'bb', 'ccc'],
['d', 'ee', 'fff']], dtype='<U3')
not_equal(x1, x2)
Return (x1 != x2) element-wise.
Unlike `numpy.not_equal`, this comparison is performed by first
stripping whitespace characters from the end of the string. This
behavior is provided for backward-compatibility with numarray.
Parameters
----------
x1, x2 : array_like of str or unicode
Input arrays of the same shape.
Returns
-------
out : ndarray
Output array of bools.
See Also
--------
equal, greater_equal, less_equal, greater, less
Examples
--------
>>> import numpy as np
>>> x1 = np.array(['a', 'b', 'c'])
>>> np.char.not_equal(x1, 'b')
array([ True, False, True])
partition(a, sep)
Partition each element in `a` around `sep`.
Calls :meth:`str.partition` element-wise.
For each element in `a`, split the element as the first
occurrence of `sep`, and return 3 strings containing the part
before the separator, the separator itself, and the part after
the separator. If the separator is not found, return 3 strings
containing the string itself, followed by two empty strings.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array
sep : {str, unicode}
Separator to split each string element in `a`.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types. The output array will have an extra
dimension with 3 elements per input element.
Examples
--------
>>> import numpy as np
>>> x = np.array(["Numpy is nice!"])
>>> np.char.partition(x, " ")
array([['Numpy', ' ', 'is nice!']], dtype='<U8')
See Also
--------
str.partition
replace(a, old, new, count=-1)
For each element in ``a``, return a copy of the string with
occurrences of substring ``old`` replaced by ``new``.
Parameters
----------
a : array_like, with ``bytes_`` or ``str_`` dtype
old, new : array_like, with ``bytes_`` or ``str_`` dtype
count : array_like, with ``int_`` dtype
If the optional argument ``count`` is given, only the first
``count`` occurrences are replaced.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.replace
Examples
--------
>>> import numpy as np
>>> a = np.array(["That is a mango", "Monkeys eat mangos"])
>>> np.strings.replace(a, 'mango', 'banana')
array(['That is a banana', 'Monkeys eat bananas'], dtype='<U19')
>>> a = np.array(["The dish is fresh", "This is it"])
>>> np.strings.replace(a, 'is', 'was')
array(['The dwash was fresh', 'Thwas was it'], dtype='<U19')
rfind(a, sub, start=0, end=None)
For each element, return the highest index in the string where
substring ``sub`` is found, such that ``sub`` is contained in the
range [``start``, ``end``).
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
The substring to search for.
start, end : array_like, with any integer dtype
The range to look in, interpreted as in slice notation.
Returns
-------
y : ndarray
Output array of ints
See Also
--------
str.rfind
Examples
--------
>>> import numpy as np
>>> a = np.array(["Computer Science"])
>>> np.strings.rfind(a, "Science", start=0, end=None)
array([9])
>>> np.strings.rfind(a, "Science", start=0, end=8)
array([-1])
>>> b = np.array(["Computer Science", "Science"])
>>> np.strings.rfind(b, "Science", start=0, end=None)
array([9, 0])
rindex(a, sub, start=0, end=None)
Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
not found.
Parameters
----------
a : array-like, with `np.bytes_` or `np.str_` dtype
sub : array-like, with `np.bytes_` or `np.str_` dtype
start, end : array-like, with any integer dtype, optional
Returns
-------
out : ndarray
Output array of ints.
See Also
--------
rfind, str.rindex
Examples
--------
>>> a = np.array(["Computer Science"])
>>> np.strings.rindex(a, "Science", start=0, end=None)
array([9])
rjust(a, width, fillchar=' ')
Return an array with the elements of `a` right-justified in a
string of length `width`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
width : array_like, with any integer dtype
The length of the resulting strings, unless ``width < str_len(a)``.
fillchar : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Optional padding character to use (default is space).
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.rjust
Notes
-----
While it is possible for ``a`` and ``fillchar`` to have different dtypes,
passing a non-ASCII character in ``fillchar`` when ``a`` is of dtype "S"
is not allowed, and a ``ValueError`` is raised.
Examples
--------
>>> import numpy as np
>>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.strings.rjust(a, width=3)
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.rjust(a, width=9)
array([' aAaAaA', ' aA ', ' abBABba'], dtype='<U9')
rpartition(a, sep)
Partition (split) each element around the right-most separator.
Calls :meth:`str.rpartition` element-wise.
For each element in `a`, split the element as the last
occurrence of `sep`, and return 3 strings containing the part
before the separator, the separator itself, and the part after
the separator. If the separator is not found, return 3 strings
containing the string itself, followed by two empty strings.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array
sep : str or unicode
Right-most separator to split each element in array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types. The output array will have an extra
dimension with 3 elements per input element.
See Also
--------
str.rpartition
Examples
--------
>>> import numpy as np
>>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.char.rpartition(a, 'A')
array([['aAaAa', 'A', ''],
[' a', 'A', ' '],
['abB', 'A', 'Bba']], dtype='<U5')
rsplit = _rsplit(a, sep=None, maxsplit=None)
For each element in `a`, return a list of the words in the
string, using `sep` as the delimiter string.
Calls :meth:`str.rsplit` element-wise.
Except for splitting from the right, `rsplit`
behaves like `split`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sep : str or unicode, optional
If `sep` is not specified or None, any whitespace string
is a separator.
maxsplit : int, optional
If `maxsplit` is given, at most `maxsplit` splits are done,
the rightmost ones.
Returns
-------
out : ndarray
Array of list objects
See Also
--------
str.rsplit, split
Examples
--------
>>> import numpy as np
>>> a = np.array(['aAaAaA', 'abBABba'])
>>> np.strings.rsplit(a, 'A') # doctest: +SKIP
array([list(['a', 'a', 'a', '']), # doctest: +SKIP
list(['abB', 'Bba'])], dtype=object) # doctest: +SKIP
rstrip(a, chars=None)
For each element in `a`, return a copy with the trailing characters
removed.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
chars : scalar with the same dtype as ``a``, optional
The ``chars`` argument is a string specifying the set of
characters to be removed. If ``None``, the ``chars``
argument defaults to removing whitespace. The ``chars`` argument
is not a prefix or suffix; rather, all combinations of its
values are stripped.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.rstrip
Examples
--------
>>> import numpy as np
>>> c = np.array(['aAaAaA', 'abBABba'])
>>> c
array(['aAaAaA', 'abBABba'], dtype='<U7')
>>> np.strings.rstrip(c, 'a')
array(['aAaAaA', 'abBABb'], dtype='<U7')
>>> np.strings.rstrip(c, 'A')
array(['aAaAa', 'abBABba'], dtype='<U7')
split = _split(a, sep=None, maxsplit=None)
For each element in `a`, return a list of the words in the
string, using `sep` as the delimiter string.
Calls :meth:`str.split` element-wise.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sep : str or unicode, optional
If `sep` is not specified or None, any whitespace string is a
separator.
maxsplit : int, optional
If `maxsplit` is given, at most `maxsplit` splits are done.
Returns
-------
out : ndarray
Array of list objects
Examples
--------
>>> import numpy as np
>>> x = np.array("Numpy is nice!")
>>> np.strings.split(x, " ") # doctest: +SKIP
array(list(['Numpy', 'is', 'nice!']), dtype=object) # doctest: +SKIP
>>> np.strings.split(x, " ", 1) # doctest: +SKIP
array(list(['Numpy', 'is nice!']), dtype=object) # doctest: +SKIP
See Also
--------
str.split, rsplit
splitlines = _splitlines(a, keepends=None)
For each element in `a`, return a list of the lines in the
element, breaking at line boundaries.
Calls :meth:`str.splitlines` element-wise.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
keepends : bool, optional
Line breaks are not included in the resulting list unless
keepends is given and true.
Returns
-------
out : ndarray
Array of list objects
See Also
--------
str.splitlines
startswith(a, prefix, start=0, end=None)
Returns a boolean array which is `True` where the string element
in ``a`` starts with ``prefix``, otherwise `False`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
prefix : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
start, end : array_like, with any integer dtype
With ``start``, test beginning at that position. With ``end``,
stop comparing at that position.
Returns
-------
out : ndarray
Output array of bools
See Also
--------
str.startswith
Examples
--------
>>> import numpy as np
>>> s = np.array(['foo', 'bar'])
>>> s
array(['foo', 'bar'], dtype='<U3')
>>> np.strings.startswith(s, 'fo')
array([True, False])
>>> np.strings.startswith(s, 'o', start=1, end=2)
array([True, False])
strip(a, chars=None)
For each element in `a`, return a copy with the leading and
trailing characters removed.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
chars : scalar with the same dtype as ``a``, optional
The ``chars`` argument is a string specifying the set of
characters to be removed. If ``None``, the ``chars``
argument defaults to removing whitespace. The ``chars`` argument
is not a prefix or suffix; rather, all combinations of its
values are stripped.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.strip
Examples
--------
>>> import numpy as np
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.strip(c)
array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7')
# 'a' unstripped from c[1] because of leading whitespace.
>>> np.strings.strip(c, 'a')
array(['AaAaA', ' aA ', 'bBABb'], dtype='<U7')
# 'A' unstripped from c[1] because of trailing whitespace.
>>> np.strings.strip(c, 'A')
array(['aAaAa', ' aA ', 'abBABba'], dtype='<U7')
swapcase(a)
Return element-wise a copy of the string with
uppercase characters converted to lowercase and vice versa.
Calls :meth:`str.swapcase` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.swapcase
Examples
--------
>>> import numpy as np
>>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c
array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'],
dtype='|S5')
>>> np.strings.swapcase(c)
array(['A1b C', '1B cA', 'B cA1', 'Ca1B'],
dtype='|S5')
title(a)
Return element-wise title cased version of string or unicode.
Title case words start with uppercase characters, all remaining cased
characters are lowercase.
Calls :meth:`str.title` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.title
Examples
--------
>>> import numpy as np
>>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c
array(['a1b c', '1b ca', 'b ca1', 'ca1b'],
dtype='|S5')
>>> np.strings.title(c)
array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
dtype='|S5')
translate(a, table, deletechars=None)
For each element in `a`, return a copy of the string where all
characters occurring in the optional argument `deletechars` are
removed, and the remaining characters have been mapped through the
given translation table.
Calls :meth:`str.translate` element-wise.
Parameters
----------
a : array-like, with `np.bytes_` or `np.str_` dtype
table : str of length 256
deletechars : str
Returns
-------
out : ndarray
Output array of str or unicode, depending on input type
See Also
--------
str.translate
Examples
--------
>>> import numpy as np
>>> a = np.array(['a1b c', '1bca', 'bca1'])
>>> table = a[0].maketrans('abc', '123')
>>> deletechars = ' '
>>> np.char.translate(a, table, deletechars)
array(['112 3', '1231', '2311'], dtype='<U5')
upper(a)
Return an array with the elements converted to uppercase.
Calls :meth:`str.upper` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.upper
Examples
--------
>>> import numpy as np
>>> c = np.array(['a1b c', '1bca', 'bca1']); c
array(['a1b c', '1bca', 'bca1'], dtype='<U5')
>>> np.strings.upper(c)
array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
zfill(a, width)
Return the numeric string left-filled with zeros. A leading
sign prefix (``+``/``-``) is handled by inserting the padding
after the sign character rather than before.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
width : array_like, with any integer dtype
Width of string to left-fill elements in `a`.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input type
See Also
--------
str.zfill
Examples
--------
>>> import numpy as np
>>> np.strings.zfill(['1', '-1', '+1'], 3)
array(['001', '-01', '+01'], dtype='<U3')
DATA
__all__ = ['equal', 'not_equal', 'greater_equal', 'less_equal', 'great...
add = <ufunc 'add'>
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
add : ndarray or scalar
The sum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.
Examples
--------
>>> import numpy as np
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
The ``+`` operator can be used as a shorthand for ``np.add`` on ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 + x2
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
isalnum = <ufunc 'isalnum'>
isalnum(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if all characters in the string are
alphanumeric and there is at least one character, false otherwise.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray
Output array of bool
This is a scalar if `x` is a scalar.
See Also
--------
str.isalnum
Examples
--------
>>> import numpy as np
>>> a = np.array(['a', '1', 'a1', '(', ''])
>>> np.strings.isalnum(a)
array([ True, True, True, False, False])
isalpha = <ufunc 'isalpha'>
isalpha(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if all characters in the data
interpreted as a string are alphabetic and there is at least
one character, false otherwise.
For byte strings (i.e. ``bytes``), alphabetic characters are
those byte values in the sequence
b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. For
Unicode strings, alphabetic characters are those characters
defined in the Unicode character database as “Letter”.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isalpha
Examples
--------
>>> import numpy as np
>>> a = np.array(['a', 'b', '0'])
>>> np.strings.isalpha(a)
array([ True, True, False])
>>> a = np.array([['a', 'b', '0'], ['c', '1', '2']])
>>> np.strings.isalpha(a)
array([[ True, True, False], [ True, False, False]])
isdecimal = <ufunc 'isdecimal'>
isdecimal(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
For each element, return True if there are only decimal
characters in the element.
Decimal characters include digit characters, and all characters
that can be used to form decimal-radix numbers,
e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``.
Parameters
----------
x : array_like, with ``StringDType`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isdecimal
Examples
--------
>>> import numpy as np
>>> np.strings.isdecimal(['12345', '4.99', '123ABC', ''])
array([ True, False, False, False])
isdigit = <ufunc 'isdigit'>
isdigit(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if all characters in the string are
digits and there is at least one character, false otherwise.
For byte strings, digits are the byte values in the sequence
b'0123456789'. For Unicode strings, digits include decimal
characters and digits that need special handling, such as the
compatibility superscript digits. This also covers digits which
cannot be used to form numbers in base 10, like the Kharosthi numbers.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isdigit
Examples
--------
>>> import numpy as np
>>> a = np.array(['a', 'b', '0'])
>>> np.strings.isdigit(a)
array([False, False, True])
>>> a = np.array([['a', 'b', '0'], ['c', '1', '2']])
>>> np.strings.isdigit(a)
array([[False, False, True], [False, True, True]])
islower = <ufunc 'islower'>
islower(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if all cased characters in the
string are lowercase and there is at least one cased character,
false otherwise.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.islower
Examples
--------
>>> import numpy as np
>>> np.strings.islower("GHC")
array(False)
>>> np.strings.islower("ghc")
array(True)
isnumeric = <ufunc 'isnumeric'>
isnumeric(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
For each element, return True if there are only numeric
characters in the element.
Numeric characters include digit characters, and all characters
that have the Unicode numeric value property, e.g. ``U+2155,
VULGAR FRACTION ONE FIFTH``.
Parameters
----------
x : array_like, with ``StringDType`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isnumeric
Examples
--------
>>> import numpy as np
>>> np.strings.isnumeric(['123', '123abc', '9.0', '1/4', 'VIII'])
array([ True, False, False, False, False])
isspace = <ufunc 'isspace'>
isspace(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if there are only whitespace
characters in the string and there is at least one character,
false otherwise.
For byte strings, whitespace characters are the ones in the
sequence b' \t\n\r\x0b\f'. For Unicode strings, a character is
whitespace, if, in the Unicode character database, its general
category is Zs (“Separator, space”), or its bidirectional class
is one of WS, B, or S.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isspace
istitle = <ufunc 'istitle'>
istitle(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if the element is a titlecased
string and there is at least one character, false otherwise.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.istitle
Examples
--------
>>> import numpy as np
>>> np.strings.istitle("Numpy Is Great")
array(True)
>>> np.strings.istitle("Numpy is great")
array(False)
isupper = <ufunc 'isupper'>
isupper(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return true for each element if all cased characters in the
string are uppercase and there is at least one character, false
otherwise.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isupper
Examples
--------
>>> import numpy as np
>>> np.strings.isupper("GHC")
array(True)
>>> a = np.array(["hello", "HELLO", "Hello"])
>>> np.strings.isupper(a)
array([False, True, False])
str_len = <ufunc 'str_len'>
str_len(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns the length of each element. For byte strings,
this is the number of bytes, while, for Unicode strings,
it is the number of Unicode code points.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of ints
This is a scalar if `x` is a scalar.
See Also
--------
len
Examples
--------
>>> import numpy as np
>>> a = np.array(['Grace Hopper Conference', 'Open Source Day'])
>>> np.strings.str_len(a)
array([23, 15])
>>> a = np.array(['Р', 'о'])
>>> np.strings.str_len(a)
array([1, 1])
>>> a = np.array([['hello', 'world'], ['Р', 'о']])
>>> np.strings.str_len(a)
array([[5, 5], [1, 1]])
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\char\__init__.py
numpy.character
Python Library Documentation: class character in module numpy class character(flexible) | Abstract base class of all character string scalar types. | | Method resolution order: | character | flexible | generic | builtins.object | | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Data and other attributes inherited from generic: | | __hash__ = None
numpy.choose
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
choose(a, choices, out=None, mode='raise')
Construct an array from an index array and a list of arrays to choose from.
First of all, if confused or uncertain, definitely look at the Examples -
in its full generality, this function is less simple than it might
seem from the following code description (below ndi =
`numpy.lib.index_tricks`):
``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``.
But this omits some subtleties. Here is a fully general summary:
Given an "index" array (`a`) of integers and a sequence of ``n`` arrays
(`choices`), `a` and each choice array are first broadcast, as necessary,
to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
for each ``i``. Then, a new array with shape ``Ba.shape`` is created as
follows:
* if ``mode='raise'`` (the default), then, first of all, each element of
``a`` (and thus ``Ba``) must be in the range ``[0, n-1]``; now, suppose
that ``i`` (in that range) is the value at the ``(j0, j1, ..., jm)``
position in ``Ba`` - then the value at the same position in the new array
is the value in ``Bchoices[i]`` at that same position;
* if ``mode='wrap'``, values in `a` (and thus `Ba`) may be any (signed)
integer; modular arithmetic is used to map integers outside the range
`[0, n-1]` back into that range; and then the new array is constructed
as above;
* if ``mode='clip'``, values in `a` (and thus ``Ba``) may be any (signed)
integer; negative integers are mapped to 0; values greater than ``n-1``
are mapped to ``n-1``; and then the new array is constructed as above.
Parameters
----------
a : int array
This array must contain integers in ``[0, n-1]``, where ``n`` is the
number of choices, unless ``mode=wrap`` or ``mode=clip``, in which
cases any integers are permissible.
choices : sequence of arrays
Choice arrays. `a` and all of the choices must be broadcastable to the
same shape. If `choices` is itself an array (not recommended), then
its outermost dimension (i.e., the one corresponding to
``choices.shape[0]``) is taken as defining the "sequence".
out : array, optional
If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype. Note that `out` is always
buffered if ``mode='raise'``; use other modes for better performance.
mode : {'raise' (default), 'wrap', 'clip'}, optional
Specifies how indices outside ``[0, n-1]`` will be treated:
* 'raise' : an exception is raised
* 'wrap' : value becomes value mod ``n``
* 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
Returns
-------
merged_array : array
The merged result.
Raises
------
ValueError: shape mismatch
If `a` and each choice array are not all broadcastable to the same
shape.
See Also
--------
ndarray.choose : equivalent method
numpy.take_along_axis : Preferable if `choices` is an array
Notes
-----
To reduce the chance of misinterpretation, even though the following
"abuse" is nominally supported, `choices` should neither be, nor be
thought of as, a single array, i.e., the outermost sequence-like container
should be either a list or a tuple.
Examples
--------
>>> import numpy as np
>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
... [20, 21, 22, 23], [30, 31, 32, 33]]
>>> np.choose([2, 3, 1, 0], choices
... # the first element of the result will be the first element of the
... # third (2+1) "array" in choices, namely, 20; the second element
... # will be the second element of the fourth (3+1) choice array, i.e.,
... # 31, etc.
... )
array([20, 31, 12, 3])
>>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
array([20, 31, 12, 3])
>>> # because there are 4 choice arrays
>>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
array([20, 1, 12, 3])
>>> # i.e., 0
A couple examples illustrating how choose broadcasts:
>>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
>>> choices = [-10, 10]
>>> np.choose(a, choices)
array([[ 10, -10, 10],
[-10, 10, -10],
[ 10, -10, 10]])
>>> # With thanks to Anne Archibald
>>> a = np.array([0, 1]).reshape((2,1,1))
>>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
>>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
>>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
array([[[ 1, 1, 1, 1, 1],
[ 2, 2, 2, 2, 2],
[ 3, 3, 3, 3, 3]],
[[-1, -2, -3, -4, -5],
[-1, -2, -3, -4, -5],
[-1, -2, -3, -4, -5]]])
numpy.clip
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
clip(a, a_min=<no value>, a_max=<no value>, out=None, *, min=<no value>, max=<no value>, **kwargs)
Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to
the interval edges. For example, if an interval of ``[0, 1]``
is specified, values smaller than 0 become 0, and values larger
than 1 become 1.
Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
No check is performed to ensure ``a_min < a_max``.
Parameters
----------
a : array_like
Array containing elements to clip.
a_min, a_max : array_like or None
Minimum and maximum value. If ``None``, clipping is not performed on
the corresponding edge. If both ``a_min`` and ``a_max`` are ``None``,
the elements of the returned array stay the same. Both are broadcasted
against ``a``.
out : ndarray, optional
The results will be placed in this array. It may be the input
array for in-place clipping. `out` must be of the right shape
to hold the output. Its type is preserved.
min, max : array_like or None
Array API compatible alternatives for ``a_min`` and ``a_max``
arguments. Either ``a_min`` and ``a_max`` or ``min`` and ``max``
can be passed at the same time. Default: ``None``.
.. versionadded:: 2.1.0
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
.. versionadded:: 1.17.0
Returns
-------
clipped_array : ndarray
An array with the elements of `a`, but where values
< `a_min` are replaced with `a_min`, and those > `a_max`
with `a_max`.
See Also
--------
:ref:`ufuncs-output-type`
Notes
-----
When `a_min` is greater than `a_max`, `clip` returns an
array in which all values are equal to `a_max`,
as shown in the second example.
Examples
--------
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, 1, 8)
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> np.clip(a, 8, 1)
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
>>> np.clip(a, 3, 6, out=a)
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
numpy.clongdouble
Python Library Documentation: class clongdouble in module numpy class clongdouble(complexfloating) | Complex number type composed of two extended-precision floating-point | numbers. | | :Character code: ``'G'`` | | Method resolution order: | clongdouble | complexfloating | inexact | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __complex__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from complexfloating: | | __round__(...) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __reduce__(...) | Helper for pickle. | | __rlshift__(self, value, /) | Return value<<self. | | __ror__(self, value, /) | Return value|self. | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.column_stack
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
column_stack(tup)
Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`. 1-D arrays are turned into 2-D columns
first.
Parameters
----------
tup : sequence of 1-D or 2-D arrays.
Arrays to stack. All of them must have the same first dimension.
Returns
-------
stacked : 2-D array
The array formed by stacking the given arrays.
See Also
--------
stack, hstack, vstack, concatenate
Examples
--------
>>> import numpy as np
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
numpy.common_type
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
common_type(*arrays)
Return a scalar type which is common to the input arrays.
The return type will always be an inexact (i.e. floating point) scalar
type, even if all the arrays are integer arrays. If one of the inputs is
an integer array, the minimum precision type that is returned is a
64-bit floating point dtype.
All input arrays except int64 and uint64 can be safely cast to the
returned dtype without loss of information.
Parameters
----------
array1, array2, ... : ndarrays
Input arrays.
Returns
-------
out : data type code
Data type code.
See Also
--------
dtype, mintypecode
Examples
--------
>>> np.common_type(np.arange(2, dtype=np.float32))
<class 'numpy.float32'>
>>> np.common_type(np.arange(2, dtype=np.float32), np.arange(2))
<class 'numpy.float64'>
>>> np.common_type(np.arange(4), np.array([45, 6.j]), np.array([45.0]))
<class 'numpy.complex128'>
numpy.complex128
Python Library Documentation: class complex128 in module numpy class complex128(complexfloating, builtins.complex) | complex128(real=0, imag=0) | | Complex number type composed of two double-precision floating-point | numbers, compatible with Python :class:`complex`. | | :Character code: ``'D'`` | :Canonical name: `numpy.cdouble` | :Alias on this platform (win32 AMD64): `numpy.complex128`: Complex number type composed of 2 64-bit-precision floating-point numbers. | | Method resolution order: | complex128 | complexfloating | inexact | number | generic | builtins.complex | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from complexfloating: | | __round__(...) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __reduce__(...) | Helper for pickle. | | __rlshift__(self, value, /) | Return value<<self. | | __ror__(self, value, /) | Return value|self. | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Methods inherited from builtins.complex: | | __complex__(self, /) | Convert this value to exact type complex. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(self, /)
numpy.complex64
Python Library Documentation: class complex64 in module numpy class complex64(complexfloating) | Complex number type composed of two single-precision floating-point | numbers. | | :Character code: ``'F'`` | :Canonical name: `numpy.csingle` | :Alias on this platform (win32 AMD64): `numpy.complex64`: Complex number type composed of 2 32-bit-precision floating-point numbers. | | Method resolution order: | complex64 | complexfloating | inexact | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __complex__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from complexfloating: | | __round__(...) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __reduce__(...) | Helper for pickle. | | __rlshift__(self, value, /) | Return value<<self. | | __ror__(self, value, /) | Return value|self. | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.complexfloating
Python Library Documentation: class complexfloating in module numpy class complexfloating(inexact) | Abstract base class of all complex number scalar types that are made up of | floating-point numbers. | | Method resolution order: | complexfloating | inexact | number | generic | builtins.object | | Methods defined here: | | __round__(...) | | ---------------------------------------------------------------------- | Class methods inherited from number: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Data and other attributes inherited from generic: | | __hash__ = None
numpy.compress
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
compress(condition, a, axis=None, out=None)
Return selected slices of an array along given axis.
When working along a given axis, a slice along that axis is returned in
`output` for each index where `condition` evaluates to True. When
working on a 1-D array, `compress` is equivalent to `extract`.
Parameters
----------
condition : 1-D array of bools
Array that selects which entries to return. If len(condition)
is less than the size of `a` along the given axis, then output is
truncated to the length of the condition array.
a : array_like
Array from which to extract a part.
axis : int, optional
Axis along which to take slices. If None (default), work on the
flattened array.
out : ndarray, optional
Output array. Its type is preserved and it must be of the right
shape to hold the output.
Returns
-------
compressed_array : ndarray
A copy of `a` without the slices along axis for which `condition`
is false.
See Also
--------
take, choose, diag, diagonal, select
ndarray.compress : Equivalent method in ndarray
extract : Equivalent method when working on 1-D arrays
:ref:`ufuncs-output-type`
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4], [5, 6]])
>>> a
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.compress([0, 1], a, axis=0)
array([[3, 4]])
>>> np.compress([False, True, True], a, axis=0)
array([[3, 4],
[5, 6]])
>>> np.compress([False, True], a, axis=1)
array([[2],
[4],
[6]])
Working on the flattened array does not return slices along an axis but
selects elements.
>>> np.compress([False, True], a)
array([2])
numpy.concat
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
concatenate(...)
concatenate(
(a1, a2, ...),
axis=0,
out=None,
dtype=None,
casting="same_kind"
)
Join a sequence of arrays along an existing axis.
Parameters
----------
a1, a2, ... : sequence of array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. If axis is None,
arrays are flattened before use. Default is 0.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what concatenate would have returned if no
out argument were specified.
dtype : str or dtype
If provided, the destination array will have this dtype. Cannot be
provided together with `out`.
.. versionadded:: 1.20.0
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'same_kind'.
For a description of the options, please see :term:`casting`.
.. versionadded:: 1.20.0
Returns
-------
res : ndarray
The concatenated array.
See Also
--------
ma.concatenate : Concatenate function that preserves input masks.
array_split : Split an array into multiple sub-arrays of equal or
near-equal size.
split : Split array into a list of multiple sub-arrays of equal size.
hsplit : Split array into multiple sub-arrays horizontally (column wise).
vsplit : Split array into multiple sub-arrays vertically (row wise).
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
stack : Stack a sequence of arrays along a new axis.
block : Assemble arrays from blocks.
hstack : Stack arrays in sequence horizontally (column wise).
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
column_stack : Stack 1-D arrays as columns into a 2-D array.
Notes
-----
When one or more of the arrays to be concatenated is a MaskedArray,
this function will return a MaskedArray object instead of an ndarray,
but the input masks are *not* preserved. In cases where a MaskedArray
is expected as input, use the ma.concatenate function from the masked
array module instead.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
[3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])
This function will not preserve masking of MaskedArray inputs.
>>> a = np.ma.arange(3)
>>> a[1] = np.ma.masked
>>> b = np.arange(2, 5)
>>> a
masked_array(data=[0, --, 2],
mask=[False, True, False],
fill_value=999999)
>>> b
array([2, 3, 4])
>>> np.concatenate([a, b])
masked_array(data=[0, 1, 2, 2, 3, 4],
mask=False,
fill_value=999999)
>>> np.ma.concatenate([a, b])
masked_array(data=[0, --, 2, 2, 3, 4],
mask=[False, True, False, False, False, False],
fill_value=999999)
numpy.concatenate
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
concatenate(...)
concatenate(
(a1, a2, ...),
axis=0,
out=None,
dtype=None,
casting="same_kind"
)
Join a sequence of arrays along an existing axis.
Parameters
----------
a1, a2, ... : sequence of array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. If axis is None,
arrays are flattened before use. Default is 0.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what concatenate would have returned if no
out argument were specified.
dtype : str or dtype
If provided, the destination array will have this dtype. Cannot be
provided together with `out`.
.. versionadded:: 1.20.0
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'same_kind'.
For a description of the options, please see :term:`casting`.
.. versionadded:: 1.20.0
Returns
-------
res : ndarray
The concatenated array.
See Also
--------
ma.concatenate : Concatenate function that preserves input masks.
array_split : Split an array into multiple sub-arrays of equal or
near-equal size.
split : Split array into a list of multiple sub-arrays of equal size.
hsplit : Split array into multiple sub-arrays horizontally (column wise).
vsplit : Split array into multiple sub-arrays vertically (row wise).
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
stack : Stack a sequence of arrays along a new axis.
block : Assemble arrays from blocks.
hstack : Stack arrays in sequence horizontally (column wise).
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
column_stack : Stack 1-D arrays as columns into a 2-D array.
Notes
-----
When one or more of the arrays to be concatenated is a MaskedArray,
this function will return a MaskedArray object instead of an ndarray,
but the input masks are *not* preserved. In cases where a MaskedArray
is expected as input, use the ma.concatenate function from the masked
array module instead.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
[3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])
This function will not preserve masking of MaskedArray inputs.
>>> a = np.ma.arange(3)
>>> a[1] = np.ma.masked
>>> b = np.arange(2, 5)
>>> a
masked_array(data=[0, --, 2],
mask=[False, True, False],
fill_value=999999)
>>> b
array([2, 3, 4])
>>> np.concatenate([a, b])
masked_array(data=[0, 1, 2, 2, 3, 4],
mask=False,
fill_value=999999)
>>> np.ma.concatenate([a, b])
masked_array(data=[0, --, 2, 2, 3, 4],
mask=[False, True, False, False, False, False],
fill_value=999999)
numpy.conj
Python Library Documentation: ufunc
conjugate = <ufunc 'conjugate'>
conjugate(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the complex conjugate, element-wise.
The complex conjugate of a complex number is obtained by changing the
sign of its imaginary part.
Parameters
----------
x : array_like
Input value.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The complex conjugate of `x`, with same dtype as `y`.
This is a scalar if `x` is a scalar.
Notes
-----
`conj` is an alias for `conjugate`:
>>> np.conj is np.conjugate
True
Examples
--------
>>> import numpy as np
>>> np.conjugate(1+2j)
(1-2j)
>>> x = np.eye(2) + 1j * np.eye(2)
>>> np.conjugate(x)
array([[ 1.-1.j, 0.-0.j],
[ 0.-0.j, 1.-1.j]])
numpy.conjugate
Python Library Documentation: ufunc
conjugate = <ufunc 'conjugate'>
conjugate(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the complex conjugate, element-wise.
The complex conjugate of a complex number is obtained by changing the
sign of its imaginary part.
Parameters
----------
x : array_like
Input value.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The complex conjugate of `x`, with same dtype as `y`.
This is a scalar if `x` is a scalar.
Notes
-----
`conj` is an alias for `conjugate`:
>>> np.conj is np.conjugate
True
Examples
--------
>>> import numpy as np
>>> np.conjugate(1+2j)
(1-2j)
>>> x = np.eye(2) + 1j * np.eye(2)
>>> np.conjugate(x)
array([[ 1.-1.j, 0.-0.j],
[ 0.-0.j, 1.-1.j]])
numpy.convolve
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
convolve(a, v, mode='full')
Returns the discrete, linear convolution of two one-dimensional sequences.
The convolution operator is often seen in signal processing, where it
models the effect of a linear time-invariant system on a signal [1]_. In
probability theory, the sum of two independent random variables is
distributed according to the convolution of their individual
distributions.
If `v` is longer than `a`, the arrays are swapped before computation.
Parameters
----------
a : (N,) array_like
First one-dimensional input array.
v : (M,) array_like
Second one-dimensional input array.
mode : {'full', 'valid', 'same'}, optional
'full':
By default, mode is 'full'. This returns the convolution
at each point of overlap, with an output shape of (N+M-1,). At
the end-points of the convolution, the signals do not overlap
completely, and boundary effects may be seen.
'same':
Mode 'same' returns output of length ``max(M, N)``. Boundary
effects are still visible.
'valid':
Mode 'valid' returns output of length
``max(M, N) - min(M, N) + 1``. The convolution product is only given
for points where the signals overlap completely. Values outside
the signal boundary have no effect.
Returns
-------
out : ndarray
Discrete, linear convolution of `a` and `v`.
See Also
--------
scipy.signal.fftconvolve : Convolve two arrays using the Fast Fourier
Transform.
scipy.linalg.toeplitz : Used to construct the convolution operator.
polymul : Polynomial multiplication. Same output as convolve, but also
accepts poly1d objects as input.
Notes
-----
The discrete convolution operation is defined as
.. math:: (a * v)_n = \sum_{m = -\infty}^{\infty} a_m v_{n - m}
It can be shown that a convolution :math:`x(t) * y(t)` in time/space
is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
domain, after appropriate padding (padding is necessary to prevent
circular convolution). Since multiplication is more efficient (faster)
than convolution, the function `scipy.signal.fftconvolve` exploits the
FFT to calculate the convolution of large data-sets.
References
----------
.. [1] Wikipedia, "Convolution",
https://en.wikipedia.org/wiki/Convolution
Examples
--------
Note how the convolution operator flips the second array
before "sliding" the two across one another:
>>> import numpy as np
>>> np.convolve([1, 2, 3], [0, 1, 0.5])
array([0. , 1. , 2.5, 4. , 1.5])
Only return the middle values of the convolution.
Contains boundary effects, where zeros are taken
into account:
>>> np.convolve([1,2,3],[0,1,0.5], 'same')
array([1. , 2.5, 4. ])
The two arrays are of the same length, so there
is only one position where they completely overlap:
>>> np.convolve([1,2,3],[0,1,0.5], 'valid')
array([2.5])
numpy.copy
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
copy(a, order='K', subok=False)
Return an array copy of the given object.
Parameters
----------
a : array_like
Input data.
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout of the copy. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'C' otherwise. 'K' means match the layout of `a` as closely
as possible. (Note that this function and :meth:`ndarray.copy` are very
similar, but have different default values for their order=
arguments.)
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise the
returned array will be forced to be a base-class array (defaults to False).
.. versionadded:: 1.19.0
Returns
-------
arr : ndarray
Array interpretation of `a`.
See Also
--------
ndarray.copy : Preferred method for creating an array copy
Notes
-----
This is equivalent to:
>>> np.array(a, copy=True) #doctest: +SKIP
The copy made of the data is shallow, i.e., for arrays with object dtype,
the new array will point to the same objects.
See Examples from `ndarray.copy`.
Examples
--------
>>> import numpy as np
Create an array x, with a reference y and a copy z:
>>> x = np.array([1, 2, 3])
>>> y = x
>>> z = np.copy(x)
Note that, when we modify x, y changes, but not z:
>>> x[0] = 10
>>> x[0] == y[0]
True
>>> x[0] == z[0]
False
Note that, np.copy clears previously set WRITEABLE=False flag.
>>> a = np.array([1, 2, 3])
>>> a.flags["WRITEABLE"] = False
>>> b = np.copy(a)
>>> b.flags["WRITEABLE"]
True
>>> b[0] = 3
>>> b
array([3, 2, 3])
numpy.copysign
Python Library Documentation: ufunc
copysign = <ufunc 'copysign'>
copysign(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Change the sign of x1 to that of x2, element-wise.
If `x2` is a scalar, its sign will be copied to all elements of `x1`.
Parameters
----------
x1 : array_like
Values to change the sign of.
x2 : array_like
The sign of `x2` is copied to `x1`.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
The values of `x1` with the sign of `x2`.
This is a scalar if both `x1` and `x2` are scalars.
Examples
--------
>>> import numpy as np
>>> np.copysign(1.3, -1)
-1.3
>>> 1/np.copysign(0, 1)
inf
>>> 1/np.copysign(0, -1)
-inf
>>> np.copysign([-1, 0, 1], -1.1)
array([-1., -0., -1.])
>>> np.copysign([-1, 0, 1], np.arange(3)-1)
array([-1., 0., 1.])
numpy.copyto
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
copyto(...)
copyto(dst, src, casting='same_kind', where=True)
Copies values from one array to another, broadcasting as necessary.
Raises a TypeError if the `casting` rule is violated, and if
`where` is provided, it selects which elements to copy.
.. versionadded:: 1.7.0
Parameters
----------
dst : ndarray
The array into which values are copied.
src : array_like
The array from which values are copied.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur when copying.
* 'no' means the data types should not be cast at all.
* 'equiv' means only byte-order changes are allowed.
* 'safe' means only casts which can preserve values are allowed.
* 'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
* 'unsafe' means any data conversions may be done.
where : array_like of bool, optional
A boolean array which is broadcasted to match the dimensions
of `dst`, and selects elements to copy from `src` to `dst`
wherever it contains the value True.
Examples
--------
>>> import numpy as np
>>> A = np.array([4, 5, 6])
>>> B = [1, 2, 3]
>>> np.copyto(A, B)
>>> A
array([1, 2, 3])
>>> A = np.array([[1, 2, 3], [4, 5, 6]])
>>> B = [[4, 5, 6], [7, 8, 9]]
>>> np.copyto(A, B)
>>> A
array([[4, 5, 6],
[7, 8, 9]])
numpy.core
Python Library Documentation: package numpy.core in numpy
NAME
numpy.core
DESCRIPTION
The `numpy.core` submodule exists solely for backward compatibility
purposes. The original `core` was renamed to `_core` and made private.
`numpy.core` will be removed in the future.
PACKAGE CONTENTS
_dtype
_dtype_ctypes
_internal
_multiarray_umath
_utils
arrayprint
defchararray
einsumfunc
fromnumeric
function_base
getlimits
multiarray
numeric
numerictypes
overrides
records
shape_base
umath
FUNCTIONS
__getattr__(attr_name)
DATA
__all__ = ['arrayprint', 'defchararray', '_dtype_ctypes', '_dtype', 'e...
VERSION
2.1.3
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\core\__init__.py
numpy.corrcoef
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
corrcoef(x, y=None, rowvar=True, bias=<no value>, ddof=<no value>, *, dtype=None)
Return Pearson product-moment correlation coefficients.
Please refer to the documentation for `cov` for more detail. The
relationship between the correlation coefficient matrix, `R`, and the
covariance matrix, `C`, is
.. math:: R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} C_{jj} } }
The values of `R` are between -1 and 1, inclusive.
Parameters
----------
x : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `x` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same
shape as `x`.
rowvar : bool, optional
If `rowvar` is True (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : _NoValue, optional
Has no effect, do not use.
.. deprecated:: 1.10.0
ddof : _NoValue, optional
Has no effect, do not use.
.. deprecated:: 1.10.0
dtype : data-type, optional
Data-type of the result. By default, the return data-type will have
at least `numpy.float64` precision.
.. versionadded:: 1.20
Returns
-------
R : ndarray
The correlation coefficient matrix of the variables.
See Also
--------
cov : Covariance matrix
Notes
-----
Due to floating point rounding the resulting array may not be Hermitian,
the diagonal elements may not be 1, and the elements may not satisfy the
inequality abs(a) <= 1. The real and imaginary parts are clipped to the
interval [-1, 1] in an attempt to improve on that situation but is not
much help in the complex case.
This function accepts but discards arguments `bias` and `ddof`. This is
for backwards compatibility with previous versions of this function. These
arguments had no effect on the return values of the function and can be
safely ignored in this and previous versions of numpy.
Examples
--------
>>> import numpy as np
In this example we generate two random arrays, ``xarr`` and ``yarr``, and
compute the row-wise and column-wise Pearson correlation coefficients,
``R``. Since ``rowvar`` is true by default, we first find the row-wise
Pearson correlation coefficients between the variables of ``xarr``.
>>> import numpy as np
>>> rng = np.random.default_rng(seed=42)
>>> xarr = rng.random((3, 3))
>>> xarr
array([[0.77395605, 0.43887844, 0.85859792],
[0.69736803, 0.09417735, 0.97562235],
[0.7611397 , 0.78606431, 0.12811363]])
>>> R1 = np.corrcoef(xarr)
>>> R1
array([[ 1. , 0.99256089, -0.68080986],
[ 0.99256089, 1. , -0.76492172],
[-0.68080986, -0.76492172, 1. ]])
If we add another set of variables and observations ``yarr``, we can
compute the row-wise Pearson correlation coefficients between the
variables in ``xarr`` and ``yarr``.
>>> yarr = rng.random((3, 3))
>>> yarr
array([[0.45038594, 0.37079802, 0.92676499],
[0.64386512, 0.82276161, 0.4434142 ],
[0.22723872, 0.55458479, 0.06381726]])
>>> R2 = np.corrcoef(xarr, yarr)
>>> R2
array([[ 1. , 0.99256089, -0.68080986, 0.75008178, -0.934284 ,
-0.99004057],
[ 0.99256089, 1. , -0.76492172, 0.82502011, -0.97074098,
-0.99981569],
[-0.68080986, -0.76492172, 1. , -0.99507202, 0.89721355,
0.77714685],
[ 0.75008178, 0.82502011, -0.99507202, 1. , -0.93657855,
-0.83571711],
[-0.934284 , -0.97074098, 0.89721355, -0.93657855, 1. ,
0.97517215],
[-0.99004057, -0.99981569, 0.77714685, -0.83571711, 0.97517215,
1. ]])
Finally if we use the option ``rowvar=False``, the columns are now
being treated as the variables and we will find the column-wise Pearson
correlation coefficients between variables in ``xarr`` and ``yarr``.
>>> R3 = np.corrcoef(xarr, yarr, rowvar=False)
>>> R3
array([[ 1. , 0.77598074, -0.47458546, -0.75078643, -0.9665554 ,
0.22423734],
[ 0.77598074, 1. , -0.92346708, -0.99923895, -0.58826587,
-0.44069024],
[-0.47458546, -0.92346708, 1. , 0.93773029, 0.23297648,
0.75137473],
[-0.75078643, -0.99923895, 0.93773029, 1. , 0.55627469,
0.47536961],
[-0.9665554 , -0.58826587, 0.23297648, 0.55627469, 1. ,
-0.46666491],
[ 0.22423734, -0.44069024, 0.75137473, 0.47536961, -0.46666491,
1. ]])
numpy.correlate
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
correlate(a, v, mode='valid')
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal
processing texts [1]_:
.. math:: c_k = \sum_n a_{n+k} \cdot \overline{v}_n
with a and v sequences being zero-padded where necessary and
:math:`\overline v` denoting complex conjugation.
Parameters
----------
a, v : array_like
Input sequences.
mode : {'valid', 'same', 'full'}, optional
Refer to the `convolve` docstring. Note that the default
is 'valid', unlike `convolve`, which uses 'full'.
Returns
-------
out : ndarray
Discrete cross-correlation of `a` and `v`.
See Also
--------
convolve : Discrete, linear convolution of two one-dimensional sequences.
scipy.signal.correlate : uses FFT which has superior performance
on large arrays.
Notes
-----
The definition of correlation above is not unique and sometimes
correlation may be defined differently. Another common definition is [1]_:
.. math:: c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}}
which is related to :math:`c_k` by :math:`c'_k = c_{-k}`.
`numpy.correlate` may perform slowly in large arrays (i.e. n = 1e5)
because it does not use the FFT to compute the convolution; in that case,
`scipy.signal.correlate` might be preferable.
References
----------
.. [1] Wikipedia, "Cross-correlation",
https://en.wikipedia.org/wiki/Cross-correlation
Examples
--------
>>> import numpy as np
>>> np.correlate([1, 2, 3], [0, 1, 0.5])
array([3.5])
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "same")
array([2. , 3.5, 3. ])
>>> np.correlate([1, 2, 3], [0, 1, 0.5], "full")
array([0.5, 2. , 3.5, 3. , 0. ])
Using complex sequences:
>>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full')
array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ])
Note that you get the time reversed, complex conjugated result
(:math:`\overline{c_{-k}}`) when the two input sequences a and v change
places:
>>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full')
array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
numpy.cos
Python Library Documentation: ufunc
cos = <ufunc 'cos'>
cos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Cosine element-wise.
Parameters
----------
x : array_like
Input array in radians.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding cosine values.
This is a scalar if `x` is a scalar.
Notes
-----
If `out` is provided, the function writes the result into it,
and returns a reference to `out`. (See Examples)
References
----------
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.
New York, NY: Dover, 1972.
Examples
--------
>>> import numpy as np
>>> np.cos(np.array([0, np.pi/2, np.pi]))
array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00])
>>>
>>> # Example of providing the optional output parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.cos([0.1], out1)
>>> out2 is out1
True
>>>
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.cos(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
numpy.cosh
Python Library Documentation: ufunc
cosh = <ufunc 'cosh'>
cosh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Hyperbolic cosine, element-wise.
Equivalent to ``1/2 * (np.exp(x) + np.exp(-x))`` and ``np.cos(1j*x)``.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Output array of same shape as `x`.
This is a scalar if `x` is a scalar.
Examples
--------
>>> import numpy as np
>>> np.cosh(0)
1.0
The hyperbolic cosine describes the shape of a hanging cable:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-4, 4, 1000)
>>> plt.plot(x, np.cosh(x))
>>> plt.show()
numpy.count_nonzero
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
count_nonzero(a, axis=None, *, keepdims=False)
Counts the number of non-zero values in the array ``a``.
The word "non-zero" is in reference to the Python 2.x
built-in method ``__nonzero__()`` (renamed ``__bool__()``
in Python 3.x) of Python objects that tests an object's
"truthfulness". For example, any number is considered
truthful if it is nonzero, whereas any string is considered
truthful if it is not the empty string. Thus, this function
(recursively) counts how many elements in ``a`` (and in
sub-arrays thereof) have their ``__nonzero__()`` or ``__bool__()``
method evaluated to ``True``.
Parameters
----------
a : array_like
The array for which to count non-zeros.
axis : int or tuple, optional
Axis or tuple of axes along which to count non-zeros.
Default is None, meaning that non-zeros will be counted
along a flattened version of ``a``.
.. versionadded:: 1.12.0
keepdims : bool, optional
If this is set to True, the axes that are counted are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
.. versionadded:: 1.19.0
Returns
-------
count : int or array of int
Number of non-zero values in the array along a given axis.
Otherwise, the total number of non-zero values in the array
is returned.
See Also
--------
nonzero : Return the coordinates of all the non-zero values.
Examples
--------
>>> import numpy as np
>>> np.count_nonzero(np.eye(4))
4
>>> a = np.array([[0, 1, 7, 0],
... [3, 0, 2, 19]])
>>> np.count_nonzero(a)
5
>>> np.count_nonzero(a, axis=0)
array([1, 1, 2, 1])
>>> np.count_nonzero(a, axis=1)
array([2, 3])
>>> np.count_nonzero(a, axis=1, keepdims=True)
array([[2],
[3]])
numpy.cov
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, *, dtype=None)
Estimate a covariance matrix, given data and weights.
Covariance indicates the level to which two variables vary together.
If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
then the covariance matrix element :math:`C_{ij}` is the covariance of
:math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
of :math:`x_i`.
See the notes for an outline of the algorithm.
Parameters
----------
m : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `m` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same form
as that of `m`.
rowvar : bool, optional
If `rowvar` is True (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : bool, optional
Default normalization (False) is by ``(N - 1)``, where ``N`` is the
number of observations given (unbiased estimate). If `bias` is True,
then normalization is by ``N``. These values can be overridden by using
the keyword ``ddof`` in numpy versions >= 1.5.
ddof : int, optional
If not ``None`` the default value implied by `bias` is overridden.
Note that ``ddof=1`` will return the unbiased estimate, even if both
`fweights` and `aweights` are specified, and ``ddof=0`` will return
the simple average. See the notes for the details. The default value
is ``None``.
.. versionadded:: 1.5
fweights : array_like, int, optional
1-D array of integer frequency weights; the number of times each
observation vector should be repeated.
.. versionadded:: 1.10
aweights : array_like, optional
1-D array of observation vector weights. These relative weights are
typically large for observations considered "important" and smaller for
observations considered less "important". If ``ddof=0`` the array of
weights can be used to assign probabilities to observation vectors.
.. versionadded:: 1.10
dtype : data-type, optional
Data-type of the result. By default, the return data-type will have
at least `numpy.float64` precision.
.. versionadded:: 1.20
Returns
-------
out : ndarray
The covariance matrix of the variables.
See Also
--------
corrcoef : Normalized covariance matrix
Notes
-----
Assume that the observations are in the columns of the observation
array `m` and let ``f = fweights`` and ``a = aweights`` for brevity. The
steps to compute the weighted covariance are as follows::
>>> m = np.arange(10, dtype=np.float64)
>>> f = np.arange(10) * 2
>>> a = np.arange(10) ** 2.
>>> ddof = 1
>>> w = f * a
>>> v1 = np.sum(w)
>>> v2 = np.sum(w * a)
>>> m -= np.sum(m * w, axis=None, keepdims=True) / v1
>>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)
Note that when ``a == 1``, the normalization factor
``v1 / (v1**2 - ddof * v2)`` goes over to ``1 / (np.sum(f) - ddof)``
as it should.
Examples
--------
>>> import numpy as np
Consider two variables, :math:`x_0` and :math:`x_1`, which
correlate perfectly, but in opposite directions:
>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> x
array([[0, 1, 2],
[2, 1, 0]])
Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
matrix shows this clearly:
>>> np.cov(x)
array([[ 1., -1.],
[-1., 1.]])
Note that element :math:`C_{0,1}`, which shows the correlation between
:math:`x_0` and :math:`x_1`, is negative.
Further, note how `x` and `y` are combined:
>>> x = [-2.1, -1, 4.3]
>>> y = [3, 1.1, 0.12]
>>> X = np.stack((x, y), axis=0)
>>> np.cov(X)
array([[11.71 , -4.286 ], # may vary
[-4.286 , 2.144133]])
>>> np.cov(x, y)
array([[11.71 , -4.286 ], # may vary
[-4.286 , 2.144133]])
>>> np.cov(x)
array(11.71)
numpy.cross
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None)
Return the cross product of two (arrays of) vectors.
The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular
to both `a` and `b`. If `a` and `b` are arrays of vectors, the vectors
are defined by the last axis of `a` and `b` by default, and these axes
can have dimensions 2 or 3. Where the dimension of either `a` or `b` is
2, the third component of the input vector is assumed to be zero and the
cross product calculated accordingly. In cases where both input vectors
have dimension 2, the z-component of the cross product is returned.
Parameters
----------
a : array_like
Components of the first vector(s).
b : array_like
Components of the second vector(s).
axisa : int, optional
Axis of `a` that defines the vector(s). By default, the last axis.
axisb : int, optional
Axis of `b` that defines the vector(s). By default, the last axis.
axisc : int, optional
Axis of `c` containing the cross product vector(s). Ignored if
both input vectors have dimension 2, as the return is scalar.
By default, the last axis.
axis : int, optional
If defined, the axis of `a`, `b` and `c` that defines the vector(s)
and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
Returns
-------
c : ndarray
Vector cross product(s).
Raises
------
ValueError
When the dimension of the vector(s) in `a` and/or `b` does not
equal 2 or 3.
See Also
--------
inner : Inner product
outer : Outer product.
linalg.cross : An Array API compatible variation of ``np.cross``,
which accepts (arrays of) 3-element vectors only.
ix_ : Construct index arrays.
Notes
-----
.. versionadded:: 1.9.0
Supports full broadcasting of the inputs.
Dimension-2 input arrays were deprecated in 2.0.0. If you do need this
functionality, you can use::
def cross2d(x, y):
return x[..., 0] * y[..., 1] - x[..., 1] * y[..., 0]
Examples
--------
Vector cross-product.
>>> import numpy as np
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([-3, 6, -3])
One vector with dimension 2.
>>> x = [1, 2]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([12, -6, -3])
Equivalently:
>>> x = [1, 2, 0]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([12, -6, -3])
Both vectors with dimension 2.
>>> x = [1,2]
>>> y = [4,5]
>>> np.cross(x, y)
array(-3)
Multiple vector cross-products. Note that the direction of the cross
product vector is defined by the *right-hand rule*.
>>> x = np.array([[1,2,3], [4,5,6]])
>>> y = np.array([[4,5,6], [1,2,3]])
>>> np.cross(x, y)
array([[-3, 6, -3],
[ 3, -6, 3]])
The orientation of `c` can be changed using the `axisc` keyword.
>>> np.cross(x, y, axisc=0)
array([[-3, 3],
[ 6, -6],
[-3, 3]])
Change the vector definition of `x` and `y` using `axisa` and `axisb`.
>>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]])
>>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]])
>>> np.cross(x, y)
array([[ -6, 12, -6],
[ 0, 0, 0],
[ 6, -12, 6]])
>>> np.cross(x, y, axisa=0, axisb=0)
array([[-24, 48, -24],
[-30, 60, -30],
[-36, 72, -36]])
numpy.csingle
Python Library Documentation: class complex64 in module numpy class complex64(complexfloating) | Complex number type composed of two single-precision floating-point | numbers. | | :Character code: ``'F'`` | :Canonical name: `numpy.csingle` | :Alias on this platform (win32 AMD64): `numpy.complex64`: Complex number type composed of 2 32-bit-precision floating-point numbers. | | Method resolution order: | complex64 | complexfloating | inexact | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __complex__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from complexfloating: | | __round__(...) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __reduce__(...) | Helper for pickle. | | __rlshift__(self, value, /) | Return value<<self. | | __ror__(self, value, /) | Return value|self. | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.ctypeslib
Python Library Documentation: module numpy.ctypeslib in numpy
NAME
numpy.ctypeslib
DESCRIPTION
============================
``ctypes`` Utility Functions
============================
See Also
--------
load_library : Load a C library.
ndpointer : Array restype/argtype with verification.
as_ctypes : Create a ctypes array from an ndarray.
as_array : Create an ndarray from a ctypes array.
References
----------
.. [1] "SciPy Cookbook: ctypes", https://scipy-cookbook.readthedocs.io/items/Ctypes.html
Examples
--------
Load the C library:
>>> _lib = np.ctypeslib.load_library('libmystuff', '.') #doctest: +SKIP
Our result type, an ndarray that must be of type double, be 1-dimensional
and is C-contiguous in memory:
>>> array_1d_double = np.ctypeslib.ndpointer(
... dtype=np.double,
... ndim=1, flags='CONTIGUOUS') #doctest: +SKIP
Our C-function typically takes an array and updates its values
in-place. For example::
void foo_func(double* x, int length)
{
int i;
for (i = 0; i < length; i++) {
x[i] = i*i;
}
}
We wrap it using:
>>> _lib.foo_func.restype = None #doctest: +SKIP
>>> _lib.foo_func.argtypes = [array_1d_double, c_int] #doctest: +SKIP
Then, we're ready to call ``foo_func``:
>>> out = np.empty(15, dtype=np.double)
>>> _lib.foo_func(out, len(out)) #doctest: +SKIP
CLASSES
_ctypes._SimpleCData(_ctypes._CData)
ctypes.c_longlong
c_intp = class c_longlong(_ctypes._SimpleCData)
| Method resolution order:
| c_longlong
| _ctypes._SimpleCData
| _ctypes._CData
| builtins.object
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __ctype_be__ = <class 'ctypes.c_longlong'>
|
| __ctype_le__ = <class 'ctypes.c_longlong'>
|
| ----------------------------------------------------------------------
| Methods inherited from _ctypes._SimpleCData:
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __ctypes_from_outparam__(...)
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods inherited from _ctypes._SimpleCData:
|
| __new__(*args, **kwargs) class method of _ctypes._SimpleCData
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _ctypes._SimpleCData:
|
| value
| current value
|
| ----------------------------------------------------------------------
| Methods inherited from _ctypes._CData:
|
| __hash__(self, /)
| Return hash(self).
|
| __reduce__(...)
| Helper for pickle.
|
| __setstate__(...)
FUNCTIONS
as_array(obj, shape=None)
Create a numpy array from a ctypes array or POINTER.
The numpy array shares the memory with the ctypes object.
The shape parameter must be given if converting from a ctypes POINTER.
The shape parameter is ignored if converting from a ctypes array
as_ctypes(obj)
Create and return a ctypes object from a numpy array. Actually
anything that exposes the __array_interface__ is accepted.
as_ctypes_type(dtype)
Convert a dtype into a ctypes type.
Parameters
----------
dtype : dtype
The dtype to convert
Returns
-------
ctype
A ctype scalar, union, array, or struct
Raises
------
NotImplementedError
If the conversion is not possible
Notes
-----
This function does not losslessly round-trip in either direction.
``np.dtype(as_ctypes_type(dt))`` will:
- insert padding fields
- reorder fields to be sorted by offset
- discard field titles
``as_ctypes_type(np.dtype(ctype))`` will:
- discard the class names of `ctypes.Structure`\ s and
`ctypes.Union`\ s
- convert single-element `ctypes.Union`\ s into single-element
`ctypes.Structure`\ s
- insert padding fields
Examples
--------
Converting a simple dtype:
>>> dt = np.dtype('int8')
>>> ctype = np.ctypeslib.as_ctypes_type(dt)
>>> ctype
<class 'ctypes.c_byte'>
Converting a structured dtype:
>>> dt = np.dtype([('x', 'i4'), ('y', 'f4')])
>>> ctype = np.ctypeslib.as_ctypes_type(dt)
>>> ctype
<class 'struct'>
load_library(libname, loader_path)
It is possible to load a library using
>>> lib = ctypes.cdll[<full_path_name>] # doctest: +SKIP
But there are cross-platform considerations, such as library file extensions,
plus the fact Windows will just load the first library it finds with that name.
NumPy supplies the load_library function as a convenience.
.. versionchanged:: 1.20.0
Allow libname and loader_path to take any
:term:`python:path-like object`.
Parameters
----------
libname : path-like
Name of the library, which can have 'lib' as a prefix,
but without an extension.
loader_path : path-like
Where the library can be found.
Returns
-------
ctypes.cdll[libpath] : library object
A ctypes library object
Raises
------
OSError
If there is no library with the expected extension, or the
library is defective and cannot be loaded.
ndpointer(dtype=None, ndim=None, shape=None, flags=None)
Array-checking restype/argtypes.
An ndpointer instance is used to describe an ndarray in restypes
and argtypes specifications. This approach is more flexible than
using, for example, ``POINTER(c_double)``, since several restrictions
can be specified, which are verified upon calling the ctypes function.
These include data type, number of dimensions, shape and flags. If a
given array does not satisfy the specified restrictions,
a ``TypeError`` is raised.
Parameters
----------
dtype : data-type, optional
Array data-type.
ndim : int, optional
Number of array dimensions.
shape : tuple of ints, optional
Array shape.
flags : str or tuple of str
Array flags; may be one or more of:
- C_CONTIGUOUS / C / CONTIGUOUS
- F_CONTIGUOUS / F / FORTRAN
- OWNDATA / O
- WRITEABLE / W
- ALIGNED / A
- WRITEBACKIFCOPY / X
Returns
-------
klass : ndpointer type object
A type object, which is an ``_ndtpr`` instance containing
dtype, ndim, shape and flags information.
Raises
------
TypeError
If a given array does not satisfy the specified restrictions.
Examples
--------
>>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64,
... ndim=1,
... flags='C_CONTIGUOUS')]
... #doctest: +SKIP
>>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64))
... #doctest: +SKIP
DATA
__all__ = ['load_library', 'ndpointer', 'c_intp', 'as_ctypes', 'as_arr...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\ctypeslib.py
numpy.cumprod
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
cumprod(a, axis=None, dtype=None, out=None)
Return the cumulative product of elements along a given axis.
Parameters
----------
a : array_like
Input array.
axis : int, optional
Axis along which the cumulative product is computed. By default
the input is flattened.
dtype : dtype, optional
Type of the returned array, as well as of the accumulator in which
the elements are multiplied. If *dtype* is not specified, it
defaults to the dtype of `a`, unless `a` has an integer dtype with
a precision less than that of the default platform integer. In
that case, the default platform integer is used instead.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type of the resulting values will be cast if necessary.
Returns
-------
cumprod : ndarray
A new array holding the result is returned unless `out` is
specified, in which case a reference to out is returned.
See Also
--------
cumulative_prod : Array API compatible alternative for ``cumprod``.
:ref:`ufuncs-output-type`
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.
Examples
--------
>>> import numpy as np
>>> a = np.array([1,2,3])
>>> np.cumprod(a) # intermediate results 1, 1*2
... # total product 1*2*3 = 6
array([1, 2, 6])
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.cumprod(a, dtype=float) # specify type of output
array([ 1., 2., 6., 24., 120., 720.])
The cumulative product for each column (i.e., over the rows) of `a`:
>>> np.cumprod(a, axis=0)
array([[ 1, 2, 3],
[ 4, 10, 18]])
The cumulative product for each row (i.e. over the columns) of `a`:
>>> np.cumprod(a,axis=1)
array([[ 1, 2, 6],
[ 4, 20, 120]])
numpy.cumsum
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
cumsum(a, axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along a given axis.
Parameters
----------
a : array_like
Input array.
axis : int, optional
Axis along which the cumulative sum is computed. The default
(None) is to compute the cumsum over the flattened array.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults
to the dtype of `a`, unless `a` has an integer dtype with a
precision less than that of the default platform integer. In
that case, the default platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary. See :ref:`ufuncs-output-type`
for more details.
Returns
-------
cumsum_along_axis : ndarray.
A new array holding the result is returned unless `out` is
specified, in which case a reference to `out` is returned. The
result has the same size as `a`, and the same shape as `a` if
`axis` is not None or `a` is a 1-d array.
See Also
--------
cumulative_sum : Array API compatible alternative for ``cumsum``.
sum : Sum array elements.
trapezoid : Integration of array values using composite trapezoidal rule.
diff : Calculate the n-th discrete difference along given axis.
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.
``cumsum(a)[-1]`` may not be equal to ``sum(a)`` for floating-point
values since ``sum`` may use a pairwise summation routine, reducing
the roundoff-error. See `sum` for more information.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1,2,3], [4,5,6]])
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> np.cumsum(a)
array([ 1, 3, 6, 10, 15, 21])
>>> np.cumsum(a, dtype=float) # specifies type of output value(s)
array([ 1., 3., 6., 10., 15., 21.])
>>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns
array([[1, 2, 3],
[5, 7, 9]])
>>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows
array([[ 1, 3, 6],
[ 4, 9, 15]])
``cumsum(b)[-1]`` may not be equal to ``sum(b)``
>>> b = np.array([1, 2e-9, 3e-9] * 1000000)
>>> b.cumsum()[-1]
1000000.0050045159
>>> b.sum()
1000000.0050000029
numpy.cumulative_prod
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
cumulative_prod(x, /, *, axis=None, dtype=None, out=None, include_initial=False)
Return the cumulative product of elements along a given axis.
This function is an Array API compatible alternative to `numpy.cumprod`.
Parameters
----------
x : array_like
Input array.
axis : int, optional
Axis along which the cumulative product is computed. The default
(None) is only allowed for one-dimensional arrays. For arrays
with more than one dimension ``axis`` is required.
dtype : dtype, optional
Type of the returned array, as well as of the accumulator in which
the elements are multiplied. If ``dtype`` is not specified, it
defaults to the dtype of ``x``, unless ``x`` has an integer dtype
with a precision less than that of the default platform integer.
In that case, the default platform integer is used instead.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type of the resulting values will be cast if necessary.
See :ref:`ufuncs-output-type` for more details.
include_initial : bool, optional
Boolean indicating whether to include the initial value (ones) as
the first value in the output. With ``include_initial=True``
the shape of the output is different than the shape of the input.
Default: ``False``.
Returns
-------
cumulative_prod_along_axis : ndarray
A new array holding the result is returned unless ``out`` is
specified, in which case a reference to ``out`` is returned. The
result has the same shape as ``x`` if ``include_initial=False``.
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.
Examples
--------
>>> a = np.array([1, 2, 3])
>>> np.cumulative_prod(a) # intermediate results 1, 1*2
... # total product 1*2*3 = 6
array([1, 2, 6])
>>> a = np.array([1, 2, 3, 4, 5, 6])
>>> np.cumulative_prod(a, dtype=float) # specify type of output
array([ 1., 2., 6., 24., 120., 720.])
The cumulative product for each column (i.e., over the rows) of ``b``:
>>> b = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.cumulative_prod(b, axis=0)
array([[ 1, 2, 3],
[ 4, 10, 18]])
The cumulative product for each row (i.e. over the columns) of ``b``:
>>> np.cumulative_prod(b, axis=1)
array([[ 1, 2, 6],
[ 4, 20, 120]])
numpy.cumulative_sum
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
cumulative_sum(x, /, *, axis=None, dtype=None, out=None, include_initial=False)
Return the cumulative sum of the elements along a given axis.
This function is an Array API compatible alternative to `numpy.cumsum`.
Parameters
----------
x : array_like
Input array.
axis : int, optional
Axis along which the cumulative sum is computed. The default
(None) is only allowed for one-dimensional arrays. For arrays
with more than one dimension ``axis`` is required.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If ``dtype`` is not specified, it defaults
to the dtype of ``x``, unless ``x`` has an integer dtype with
a precision less than that of the default platform integer.
In that case, the default platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary. See :ref:`ufuncs-output-type`
for more details.
include_initial : bool, optional
Boolean indicating whether to include the initial value (ones) as
the first value in the output. With ``include_initial=True``
the shape of the output is different than the shape of the input.
Default: ``False``.
Returns
-------
cumulative_sum_along_axis : ndarray
A new array holding the result is returned unless ``out`` is
specified, in which case a reference to ``out`` is returned. The
result has the same shape as ``x`` if ``include_initial=False``.
See Also
--------
sum : Sum array elements.
trapezoid : Integration of array values using composite trapezoidal rule.
diff : Calculate the n-th discrete difference along given axis.
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.
``cumulative_sum(a)[-1]`` may not be equal to ``sum(a)`` for
floating-point values since ``sum`` may use a pairwise summation routine,
reducing the roundoff-error. See `sum` for more information.
Examples
--------
>>> a = np.array([1, 2, 3, 4, 5, 6])
>>> a
array([1, 2, 3, 4, 5, 6])
>>> np.cumulative_sum(a)
array([ 1, 3, 6, 10, 15, 21])
>>> np.cumulative_sum(a, dtype=float) # specifies type of output value(s)
array([ 1., 3., 6., 10., 15., 21.])
>>> b = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.cumulative_sum(b,axis=0) # sum over rows for each of the 3 columns
array([[1, 2, 3],
[5, 7, 9]])
>>> np.cumulative_sum(b,axis=1) # sum over columns for each of the 2 rows
array([[ 1, 3, 6],
[ 4, 9, 15]])
``cumulative_sum(c)[-1]`` may not be equal to ``sum(c)``
>>> c = np.array([1, 2e-9, 3e-9] * 1000000)
>>> np.cumulative_sum(c)[-1]
1000000.0050045159
>>> c.sum()
1000000.0050000029
numpy.datetime64
Python Library Documentation: class datetime64 in module numpy
class datetime64(generic)
| If created from a 64-bit integer, it represents an offset from
| ``1970-01-01T00:00:00``.
| If created from string, the string can be in ISO 8601 date
| or datetime format.
|
| When parsing a string to create a datetime object, if the string contains
| a trailing timezone (A 'Z' or a timezone offset), the timezone will be
| dropped and a User Warning is given.
|
| Datetime64 objects should be considered to be UTC and therefore have an
| offset of +0000.
|
| >>> np.datetime64(10, 'Y')
| np.datetime64('1980')
| >>> np.datetime64('1980', 'Y')
| np.datetime64('1980')
| >>> np.datetime64(10, 'D')
| np.datetime64('1970-01-11')
|
| See :ref:`arrays.datetime` for more information.
|
| :Character code: ``'M'``
|
| Method resolution order:
| datetime64
| generic
| builtins.object
|
| Methods defined here:
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __str__(self, /)
| Return str(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __bool__(self, /)
| True if self else False
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| NumPy array scalar formatter
|
| __getitem__(self, key, /)
| Return self[key].
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| Helper for pickle.
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setstate__(...)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| base
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.base`.
|
| data
| Pointer to start of data.
|
| device
|
| dtype
| Get array data-descriptor.
|
| flags
| The integer value of flags.
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
numpy.datetime_as_string
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
datetime_as_string(...)
datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
Convert an array of datetimes into an array of strings.
Parameters
----------
arr : array_like of datetime64
The array of UTC timestamps to format.
unit : str
One of None, 'auto', or
a :ref:`datetime unit <arrays.dtypes.dateunits>`.
timezone : {'naive', 'UTC', 'local'} or tzinfo
Timezone information to use when displaying the datetime. If 'UTC',
end with a Z to indicate UTC time. If 'local', convert to the local
timezone first, and suffix with a +-#### timezone offset. If a tzinfo
object, then do as with 'local', but use the specified timezone.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
Casting to allow when changing between datetime units.
Returns
-------
str_arr : ndarray
An array of strings the same shape as `arr`.
Examples
--------
>>> import numpy as np
>>> import pytz
>>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]')
>>> d
array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30',
'2002-10-27T07:30'], dtype='datetime64[m]')
Setting the timezone to UTC shows the same information, but with a Z suffix
>>> np.datetime_as_string(d, timezone='UTC')
array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z',
'2002-10-27T07:30Z'], dtype='<U35')
Note that we picked datetimes that cross a DST boundary. Passing in a
``pytz`` timezone object will print the appropriate offset
>>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern'))
array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400',
'2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39')
Passing in a unit will change the precision
>>> np.datetime_as_string(d, unit='h')
array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'],
dtype='<U32')
>>> np.datetime_as_string(d, unit='s')
array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00',
'2002-10-27T07:30:00'], dtype='<U38')
'casting' can be used to specify whether precision can be changed
>>> np.datetime_as_string(d, unit='h', casting='safe')
Traceback (most recent call last):
...
TypeError: Cannot create a datetime string as units 'h' from a NumPy
datetime with units 'm' according to the rule 'safe'
numpy.datetime_data
Python Library Documentation: built-in function datetime_data in module numpy
datetime_data(...)
datetime_data(dtype, /)
Get information about the step size of a date or time type.
The returned tuple can be passed as the second argument of `numpy.datetime64` and
`numpy.timedelta64`.
Parameters
----------
dtype : dtype
The dtype object, which must be a `datetime64` or `timedelta64` type.
Returns
-------
unit : str
The :ref:`datetime unit <arrays.dtypes.dateunits>` on which this dtype
is based.
count : int
The number of base units in a step.
Examples
--------
>>> import numpy as np
>>> dt_25s = np.dtype('timedelta64[25s]')
>>> np.datetime_data(dt_25s)
('s', 25)
>>> np.array(10, dt_25s).astype('timedelta64[s]')
array(250, dtype='timedelta64[s]')
The result can be used to construct a datetime that uses the same units
as a timedelta
>>> np.datetime64('2010', np.datetime_data(dt_25s))
np.datetime64('2010-01-01T00:00:00','25s')
numpy.deg2rad
Python Library Documentation: ufunc
deg2rad = <ufunc 'deg2rad'>
deg2rad(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Convert angles from degrees to radians.
Parameters
----------
x : array_like
Angles in degrees.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding angle in radians.
This is a scalar if `x` is a scalar.
See Also
--------
rad2deg : Convert angles from radians to degrees.
unwrap : Remove large jumps in angle by wrapping.
Notes
-----
.. versionadded:: 1.3.0
``deg2rad(x)`` is ``x * pi / 180``.
Examples
--------
>>> import numpy as np
>>> np.deg2rad(180)
3.1415926535897931
numpy.degrees
Python Library Documentation: ufunc
degrees = <ufunc 'degrees'>
degrees(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Convert angles from radians to degrees.
Parameters
----------
x : array_like
Input array in radians.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray of floats
The corresponding degree values; if `out` was supplied this is a
reference to it.
This is a scalar if `x` is a scalar.
See Also
--------
rad2deg : equivalent function
Examples
--------
Convert a radian array to degrees
>>> import numpy as np
>>> rad = np.arange(12.)*np.pi/6
>>> np.degrees(rad)
array([ 0., 30., 60., 90., 120., 150., 180., 210., 240.,
270., 300., 330.])
>>> out = np.zeros((rad.shape))
>>> r = np.degrees(rad, out)
>>> np.all(r == out)
True
numpy.delete
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
delete(arr, obj, axis=None)
Return a new array with sub-arrays along an axis deleted. For a one
dimensional array, this returns those entries not returned by
`arr[obj]`.
Parameters
----------
arr : array_like
Input array.
obj : slice, int or array of ints
Indicate indices of sub-arrays to remove along the specified axis.
.. versionchanged:: 1.19.0
Boolean indices are now treated as a mask of elements to remove,
rather than being cast to the integers 0 and 1.
axis : int, optional
The axis along which to delete the subarray defined by `obj`.
If `axis` is None, `obj` is applied to the flattened array.
Returns
-------
out : ndarray
A copy of `arr` with the elements specified by `obj` removed. Note
that `delete` does not occur in-place. If `axis` is None, `out` is
a flattened array.
See Also
--------
insert : Insert elements into an array.
append : Append elements at the end of an array.
Notes
-----
Often it is preferable to use a boolean mask. For example:
>>> arr = np.arange(12) + 1
>>> mask = np.ones(len(arr), dtype=bool)
>>> mask[[0,2,4]] = False
>>> result = arr[mask,...]
Is equivalent to ``np.delete(arr, [0,2,4], axis=0)``, but allows further
use of `mask`.
Examples
--------
>>> import numpy as np
>>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> arr
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1, 2, 3, 4],
[ 9, 10, 11, 12]])
>>> np.delete(arr, np.s_[::2], 1)
array([[ 2, 4],
[ 6, 8],
[10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1, 3, 5, 7, 8, 9, 10, 11, 12])
numpy.diag
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
diag(v, k=0)
Extract a diagonal or construct a diagonal array.
See the more detailed documentation for ``numpy.diagonal`` if you use this
function to extract a diagonal and wish to write to the resulting array;
whether it returns a copy or a view depends on what version of numpy you
are using.
Parameters
----------
v : array_like
If `v` is a 2-D array, return a copy of its `k`-th diagonal.
If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
diagonal.
k : int, optional
Diagonal in question. The default is 0. Use `k>0` for diagonals
above the main diagonal, and `k<0` for diagonals below the main
diagonal.
Returns
-------
out : ndarray
The extracted diagonal or constructed diagonal array.
See Also
--------
diagonal : Return specified diagonals.
diagflat : Create a 2-D array with the flattened input as a diagonal.
trace : Sum along diagonals.
triu : Upper triangle of an array.
tril : Lower triangle of an array.
Examples
--------
>>> import numpy as np
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]])
numpy.diag_indices
Python Library Documentation: function diag_indices in module numpy
diag_indices(n, ndim=2)
Return the indices to access the main diagonal of an array.
This returns a tuple of indices that can be used to access the main
diagonal of an array `a` with ``a.ndim >= 2`` dimensions and shape
(n, n, ..., n). For ``a.ndim = 2`` this is the usual diagonal, for
``a.ndim > 2`` this is the set of indices to access ``a[i, i, ..., i]``
for ``i = [0..n-1]``.
Parameters
----------
n : int
The size, along each dimension, of the arrays for which the returned
indices can be used.
ndim : int, optional
The number of dimensions.
See Also
--------
diag_indices_from
Notes
-----
.. versionadded:: 1.4.0
Examples
--------
>>> import numpy as np
Create a set of indices to access the diagonal of a (4, 4) array:
>>> di = np.diag_indices(4)
>>> di
(array([0, 1, 2, 3]), array([0, 1, 2, 3]))
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> a[di] = 100
>>> a
array([[100, 1, 2, 3],
[ 4, 100, 6, 7],
[ 8, 9, 100, 11],
[ 12, 13, 14, 100]])
Now, we create indices to manipulate a 3-D array:
>>> d3 = np.diag_indices(2, 3)
>>> d3
(array([0, 1]), array([0, 1]), array([0, 1]))
And use it to set the diagonal of an array of zeros to 1:
>>> a = np.zeros((2, 2, 2), dtype=int)
>>> a[d3] = 1
>>> a
array([[[1, 0],
[0, 0]],
[[0, 0],
[0, 1]]])
numpy.diag_indices_from
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
diag_indices_from(arr)
Return the indices to access the main diagonal of an n-dimensional array.
See `diag_indices` for full details.
Parameters
----------
arr : array, at least 2-D
See Also
--------
diag_indices
Notes
-----
.. versionadded:: 1.4.0
Examples
--------
>>> import numpy as np
Create a 4 by 4 array.
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Get the indices of the diagonal elements.
>>> di = np.diag_indices_from(a)
>>> di
(array([0, 1, 2, 3]), array([0, 1, 2, 3]))
>>> a[di]
array([ 0, 5, 10, 15])
This is simply syntactic sugar for diag_indices.
>>> np.diag_indices(a.shape[0])
(array([0, 1, 2, 3]), array([0, 1, 2, 3]))
numpy.diagflat
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
diagflat(v, k=0)
Create a two-dimensional array with the flattened input as a diagonal.
Parameters
----------
v : array_like
Input data, which is flattened and set as the `k`-th
diagonal of the output.
k : int, optional
Diagonal to set; 0, the default, corresponds to the "main" diagonal,
a positive (negative) `k` giving the number of the diagonal above
(below) the main.
Returns
-------
out : ndarray
The 2-D output array.
See Also
--------
diag : MATLAB work-alike for 1-D and 2-D arrays.
diagonal : Return specified diagonals.
trace : Sum along diagonals.
Examples
--------
>>> import numpy as np
>>> np.diagflat([[1,2], [3,4]])
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
[0, 0, 2],
[0, 0, 0]])
numpy.diagonal
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
diagonal(a, offset=0, axis1=0, axis2=1)
Return specified diagonals.
If `a` is 2-D, returns the diagonal of `a` with the given offset,
i.e., the collection of elements of the form ``a[i, i+offset]``. If
`a` has more than two dimensions, then the axes specified by `axis1`
and `axis2` are used to determine the 2-D sub-array whose diagonal is
returned. The shape of the resulting array can be determined by
removing `axis1` and `axis2` and appending an index to the right equal
to the size of the resulting diagonals.
In versions of NumPy prior to 1.7, this function always returned a new,
independent array containing a copy of the values in the diagonal.
In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal,
but depending on this fact is deprecated. Writing to the resulting
array continues to work as it used to, but a FutureWarning is issued.
Starting in NumPy 1.9 it returns a read-only view on the original array.
Attempting to write to the resulting array will produce an error.
In some future release, it will return a read/write view and writing to
the returned array will alter your original array. The returned array
will have the same type as the input array.
If you don't write to the array returned by this function, then you can
just ignore all of the above.
If you depend on the current behavior, then we suggest copying the
returned array explicitly, i.e., use ``np.diagonal(a).copy()`` instead
of just ``np.diagonal(a)``. This will work with both past and future
versions of NumPy.
Parameters
----------
a : array_like
Array from which the diagonals are taken.
offset : int, optional
Offset of the diagonal from the main diagonal. Can be positive or
negative. Defaults to main diagonal (0).
axis1 : int, optional
Axis to be used as the first axis of the 2-D sub-arrays from which
the diagonals should be taken. Defaults to first axis (0).
axis2 : int, optional
Axis to be used as the second axis of the 2-D sub-arrays from
which the diagonals should be taken. Defaults to second axis (1).
Returns
-------
array_of_diagonals : ndarray
If `a` is 2-D, then a 1-D array containing the diagonal and of the
same type as `a` is returned unless `a` is a `matrix`, in which case
a 1-D array rather than a (2-D) `matrix` is returned in order to
maintain backward compatibility.
If ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2`
are removed, and a new axis inserted at the end corresponding to the
diagonal.
Raises
------
ValueError
If the dimension of `a` is less than 2.
See Also
--------
diag : MATLAB work-a-like for 1-D and 2-D arrays.
diagflat : Create diagonal arrays.
trace : Sum along diagonals.
Examples
--------
>>> import numpy as np
>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
[2, 3]])
>>> a.diagonal()
array([0, 3])
>>> a.diagonal(1)
array([1])
A 3-D example:
>>> a = np.arange(8).reshape(2,2,2); a
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> a.diagonal(0, # Main diagonals of two arrays created by skipping
... 0, # across the outer(left)-most axis last and
... 1) # the "middle" (row) axis first.
array([[0, 6],
[1, 7]])
The sub-arrays whose main diagonals we just obtained; note that each
corresponds to fixing the right-most (column) axis, and that the
diagonals are "packed" in rows.
>>> a[:,:,0] # main diagonal is [0 6]
array([[0, 2],
[4, 6]])
>>> a[:,:,1] # main diagonal is [1 7]
array([[1, 3],
[5, 7]])
The anti-diagonal can be obtained by reversing the order of elements
using either `numpy.flipud` or `numpy.fliplr`.
>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.fliplr(a).diagonal() # Horizontal flip
array([2, 4, 6])
>>> np.flipud(a).diagonal() # Vertical flip
array([6, 4, 2])
Note that the order in which the diagonal is retrieved varies depending
on the flip function.
numpy.diff
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)
Calculate the n-th discrete difference along the given axis.
The first difference is given by ``out[i] = a[i+1] - a[i]`` along
the given axis, higher differences are calculated by using `diff`
recursively.
Parameters
----------
a : array_like
Input array
n : int, optional
The number of times values are differenced. If zero, the input
is returned as-is.
axis : int, optional
The axis along which the difference is taken, default is the
last axis.
prepend, append : array_like, optional
Values to prepend or append to `a` along axis prior to
performing the difference. Scalar values are expanded to
arrays with length 1 in the direction of axis and the shape
of the input array in along all other axes. Otherwise the
dimension and shape must match `a` except along axis.
.. versionadded:: 1.16.0
Returns
-------
diff : ndarray
The n-th differences. The shape of the output is the same as `a`
except along `axis` where the dimension is smaller by `n`. The
type of the output is the same as the type of the difference
between any two elements of `a`. This is the same as the type of
`a` in most cases. A notable exception is `datetime64`, which
results in a `timedelta64` output array.
See Also
--------
gradient, ediff1d, cumsum
Notes
-----
Type is preserved for boolean arrays, so the result will contain
`False` when consecutive elements are the same and `True` when they
differ.
For unsigned integer arrays, the results will also be unsigned. This
should not be surprising, as the result is consistent with
calculating the difference directly:
>>> u8_arr = np.array([1, 0], dtype=np.uint8)
>>> np.diff(u8_arr)
array([255], dtype=uint8)
>>> u8_arr[1,...] - u8_arr[0,...]
255
If this is not desirable, then the array should be cast to a larger
integer type first:
>>> i16_arr = u8_arr.astype(np.int16)
>>> np.diff(i16_arr)
array([-1], dtype=int16)
Examples
--------
>>> import numpy as np
>>> x = np.array([1, 2, 4, 7, 0])
>>> np.diff(x)
array([ 1, 2, 3, -7])
>>> np.diff(x, n=2)
array([ 1, 1, -10])
>>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]])
>>> np.diff(x)
array([[2, 3, 4],
[5, 1, 2]])
>>> np.diff(x, axis=0)
array([[-1, 2, 0, -2]])
>>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
>>> np.diff(x)
array([1, 1], dtype='timedelta64[D]')
numpy.digitize
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
digitize(x, bins, right=False)
Return the indices of the bins to which each value in input array belongs.
========= ============= ============================
`right` order of bins returned index `i` satisfies
========= ============= ============================
``False`` increasing ``bins[i-1] <= x < bins[i]``
``True`` increasing ``bins[i-1] < x <= bins[i]``
``False`` decreasing ``bins[i-1] > x >= bins[i]``
``True`` decreasing ``bins[i-1] >= x > bins[i]``
========= ============= ============================
If values in `x` are beyond the bounds of `bins`, 0 or ``len(bins)`` is
returned as appropriate.
Parameters
----------
x : array_like
Input array to be binned. Prior to NumPy 1.10.0, this array had to
be 1-dimensional, but can now have any shape.
bins : array_like
Array of bins. It has to be 1-dimensional and monotonic.
right : bool, optional
Indicating whether the intervals include the right or the left bin
edge. Default behavior is (right==False) indicating that the interval
does not include the right edge. The left bin end is open in this
case, i.e., bins[i-1] <= x < bins[i] is the default behavior for
monotonically increasing bins.
Returns
-------
indices : ndarray of ints
Output array of indices, of same shape as `x`.
Raises
------
ValueError
If `bins` is not monotonic.
TypeError
If the type of the input is complex.
See Also
--------
bincount, histogram, unique, searchsorted
Notes
-----
If values in `x` are such that they fall outside the bin range,
attempting to index `bins` with the indices that `digitize` returns
will result in an IndexError.
.. versionadded:: 1.10.0
`numpy.digitize` is implemented in terms of `numpy.searchsorted`.
This means that a binary search is used to bin the values, which scales
much better for larger number of bins than the previous linear search.
It also removes the requirement for the input array to be 1-dimensional.
For monotonically *increasing* `bins`, the following are equivalent::
np.digitize(x, bins, right=True)
np.searchsorted(bins, x, side='left')
Note that as the order of the arguments are reversed, the side must be too.
The `searchsorted` call is marginally faster, as it does not do any
monotonicity checks. Perhaps more importantly, it supports all dtypes.
Examples
--------
>>> import numpy as np
>>> x = np.array([0.2, 6.4, 3.0, 1.6])
>>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
>>> inds = np.digitize(x, bins)
>>> inds
array([1, 4, 3, 2])
>>> for n in range(x.size):
... print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]])
...
0.0 <= 0.2 < 1.0
4.0 <= 6.4 < 10.0
2.5 <= 3.0 < 4.0
1.0 <= 1.6 < 2.5
>>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.])
>>> bins = np.array([0, 5, 10, 15, 20])
>>> np.digitize(x,bins,right=True)
array([1, 2, 3, 4, 4])
>>> np.digitize(x,bins,right=False)
array([1, 3, 3, 4, 5])
numpy.divide
Python Library Documentation: ufunc
divide = <ufunc 'divide'>
divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Divide arguments element-wise.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The quotient ``x1/x2``, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
seterr : Set whether to raise or warn on overflow, underflow and
division by zero.
Notes
-----
Equivalent to ``x1`` / ``x2`` in terms of array-broadcasting.
The ``true_divide(x1, x2)`` function is an alias for
``divide(x1, x2)``.
Examples
--------
>>> import numpy as np
>>> np.divide(2.0, 4.0)
0.5
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.divide(x1, x2)
array([[nan, 1. , 1. ],
[inf, 4. , 2.5],
[inf, 7. , 4. ]])
The ``/`` operator can be used as a shorthand for ``np.divide`` on
ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = 2 * np.ones(3)
>>> x1 / x2
array([[0. , 0.5, 1. ],
[1.5, 2. , 2.5],
[3. , 3.5, 4. ]])
numpy.divmod
Python Library Documentation: ufunc
divmod = <ufunc 'divmod'>
divmod(x1, x2[, out1, out2], / [, out=(None, None)], *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return element-wise quotient and remainder simultaneously.
.. versionadded:: 1.13.0
``np.divmod(x, y)`` is equivalent to ``(x // y, x % y)``, but faster
because it avoids redundant work. It is used to implement the Python
built-in function ``divmod`` on NumPy arrays.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out1 : ndarray
Element-wise quotient resulting from floor division.
This is a scalar if both `x1` and `x2` are scalars.
out2 : ndarray
Element-wise remainder from floor division.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
floor_divide : Equivalent to Python's ``//`` operator.
remainder : Equivalent to Python's ``%`` operator.
modf : Equivalent to ``divmod(x, 1)`` for positive ``x`` with the return
values switched.
Examples
--------
>>> import numpy as np
>>> np.divmod(np.arange(5), 3)
(array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))
The `divmod` function can be used as a shorthand for ``np.divmod`` on
ndarrays.
>>> x = np.arange(5)
>>> divmod(x, 3)
(array([0, 0, 0, 1, 1]), array([0, 1, 2, 0, 1]))
numpy.dot
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
dot(...)
dot(a, b, out=None)
Dot product of two arrays. Specifically,
- If both `a` and `b` are 1-D arrays, it is inner product of vectors
(without complex conjugation).
- If both `a` and `b` are 2-D arrays, it is matrix multiplication,
but using :func:`matmul` or ``a @ b`` is preferred.
- If either `a` or `b` is 0-D (scalar), it is equivalent to
:func:`multiply` and using ``numpy.multiply(a, b)`` or ``a * b`` is
preferred.
- If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
the last axis of `a` and `b`.
- If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a
sum product over the last axis of `a` and the second-to-last axis of
`b`::
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
It uses an optimized BLAS library when possible (see `numpy.linalg`).
Parameters
----------
a : array_like
First argument.
b : array_like
Second argument.
out : ndarray, optional
Output argument. This must have the exact kind that would be returned
if it was not used. In particular, it must have the right type, must be
C-contiguous, and its dtype must be the dtype that would be returned
for `dot(a,b)`. This is a performance feature. Therefore, if these
conditions are not met, an exception is raised, instead of attempting
to be flexible.
Returns
-------
output : ndarray
Returns the dot product of `a` and `b`. If `a` and `b` are both
scalars or both 1-D arrays then a scalar is returned; otherwise
an array is returned.
If `out` is given, then it is returned.
Raises
------
ValueError
If the last dimension of `a` is not the same size as
the second-to-last dimension of `b`.
See Also
--------
vdot : Complex-conjugating dot product.
tensordot : Sum products over arbitrary axes.
einsum : Einstein summation convention.
matmul : '@' operator as method with out parameter.
linalg.multi_dot : Chained dot product.
Examples
--------
>>> import numpy as np
>>> np.dot(3, 4)
12
Neither argument is complex-conjugated:
>>> np.dot([2j, 3j], [2j, 3j])
(-13+0j)
For 2-D arrays it is the matrix product:
>>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.dot(a, b)
array([[4, 1],
[2, 2]])
>>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
>>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
>>> np.dot(a, b)[2,3,2,1,2,2]
499128
>>> sum(a[2,3,2,:] * b[1,2,:,2])
499128
numpy.double
Python Library Documentation: class float64 in module numpy
class float64(floating, builtins.float)
| float64(x=0, /)
|
| Double-precision floating-point number type, compatible with Python
| :class:`float` and C ``double``.
|
| :Character code: ``'d'``
| :Canonical name: `numpy.double`
| :Alias on this platform (win32 AMD64): `numpy.float64`: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa.
|
| Method resolution order:
| float64
| floating
| inexact
| number
| generic
| builtins.float
| builtins.object
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| as_integer_ratio(...)
| double.as_integer_ratio() -> (int, int)
|
| Return a pair of integers, whose ratio is exactly equal to the original
| floating point number, and with a positive denominator.
| Raise `OverflowError` on infinities and a `ValueError` on NaNs.
|
| >>> np.double(10.0).as_integer_ratio()
| (10, 1)
| >>> np.double(0.0).as_integer_ratio()
| (0, 1)
| >>> np.double(-.25).as_integer_ratio()
| (-1, 4)
|
| is_integer(...)
| double.is_integer() -> bool
|
| Return ``True`` if the floating point number is finite with integral
| value, and ``False`` otherwise.
|
| .. versionadded:: 1.22
|
| Examples
| --------
| >>> np.double(-2.0).is_integer()
| True
| >>> np.double(3.2).is_integer()
| False
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.number` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.number` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.signedinteger[Any]
| numpy.signedinteger[typing.Any]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from floating:
|
| __round__(...)
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __format__(...)
| NumPy array scalar formatter
|
| __getitem__(self, key, /)
| Return self[key].
|
| __invert__(self, /)
| ~self
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __or__(self, value, /)
| Return self|value.
|
| __rand__(self, value, /)
| Return value&self.
|
| __reduce__(...)
| Helper for pickle.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setstate__(...)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| base
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.base`.
|
| data
| Pointer to start of data.
|
| device
|
| dtype
| Get array data-descriptor.
|
| flags
| The integer value of flags.
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.float:
|
| __ceil__(self, /)
| Return the ceiling as an Integral.
|
| __floor__(self, /)
| Return the floor as an Integral.
|
| __getnewargs__(self, /)
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> 3.14159.hex()
| '0x1.921f9f01b866ep+1'
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.float:
|
| __getformat__(typestr, /)
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
| little-endian' best describes the format of floating-point numbers used by the
| C type named by typestr.
|
| fromhex(string, /)
| Create a floating-point number from a hexadecimal string.
|
| >>> float.fromhex('0x1.ffffp10')
| 2047.984375
| >>> float.fromhex('-0x1p-1074')
| -5e-324
numpy.dsplit
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
dsplit(ary, indices_or_sections)
Split array into multiple sub-arrays along the 3rd axis (depth).
Please refer to the `split` documentation. `dsplit` is equivalent
to `split` with ``axis=2``, the array is always split along the third
axis provided the array dimension is greater than or equal to 3.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> import numpy as np
>>> x = np.arange(16.0).reshape(2, 2, 4)
>>> x
array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[12., 13., 14., 15.]]])
>>> np.dsplit(x, 2)
[array([[[ 0., 1.],
[ 4., 5.]],
[[ 8., 9.],
[12., 13.]]]), array([[[ 2., 3.],
[ 6., 7.]],
[[10., 11.],
[14., 15.]]])]
>>> np.dsplit(x, np.array([3, 6]))
[array([[[ 0., 1., 2.],
[ 4., 5., 6.]],
[[ 8., 9., 10.],
[12., 13., 14.]]]),
array([[[ 3.],
[ 7.]],
[[11.],
[15.]]]),
array([], shape=(2, 2, 0), dtype=float64)]
numpy.dstack
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
dstack(tup)
Stack arrays in sequence depth wise (along third axis).
This is equivalent to concatenation along the third axis after 2-D arrays
of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape
`(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by
`dsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of arrays
The arrays must have the same shape along all but the third axis.
1-D or 2-D arrays must have the same shape.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 3-D.
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
block : Assemble an nd-array from nested lists of blocks.
vstack : Stack arrays in sequence vertically (row wise).
hstack : Stack arrays in sequence horizontally (column wise).
column_stack : Stack 1-D arrays as columns into a 2-D array.
dsplit : Split array along third axis.
Examples
--------
>>> import numpy as np
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
numpy.dtype
Python Library Documentation: class dtype in module numpy
class dtype(builtins.object)
| dtype(dtype, align=False, copy=False, [metadata])
|
| Create a data type object.
|
| A numpy array is homogeneous, and contains elements described by a
| dtype object. A dtype object can be constructed from different
| combinations of fundamental numeric types.
|
| Parameters
| ----------
| dtype
| Object to be converted to a data type object.
| align : bool, optional
| Add padding to the fields to match what a C compiler would output
| for a similar C-struct. Can be ``True`` only if `obj` is a dictionary
| or a comma-separated string. If a struct dtype is being created,
| this also sets a sticky alignment flag ``isalignedstruct``.
| copy : bool, optional
| Make a new copy of the data-type object. If ``False``, the result
| may just be a reference to a built-in data-type object.
| metadata : dict, optional
| An optional dictionary with dtype metadata.
|
| See also
| --------
| result_type
|
| Examples
| --------
| Using array-scalar type:
|
| >>> import numpy as np
| >>> np.dtype(np.int16)
| dtype('int16')
|
| Structured type, one field name 'f1', containing int16:
|
| >>> np.dtype([('f1', np.int16)])
| dtype([('f1', '<i2')])
|
| Structured type, one field named 'f1', in itself containing a structured
| type with one field:
|
| >>> np.dtype([('f1', [('f1', np.int16)])])
| dtype([('f1', [('f1', '<i2')])])
|
| Structured type, two fields: the first field contains an unsigned int, the
| second an int32:
|
| >>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
| dtype([('f1', '<u8'), ('f2', '<i4')])
|
| Using array-protocol type strings:
|
| >>> np.dtype([('a','f8'),('b','S10')])
| dtype([('a', '<f8'), ('b', 'S10')])
|
| Using comma-separated field formats. The shape is (2,3):
|
| >>> np.dtype("i4, (2,3)f8")
| dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])
|
| Using tuples. ``int`` is a fixed type, 3 the field's shape. ``void``
| is a flexible type, here of size 10:
|
| >>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
| dtype([('hello', '<i8', (3,)), ('world', 'V10')])
|
| Subdivide ``int16`` into 2 ``int8``'s, called x and y. 0 and 1 are
| the offsets in bytes:
|
| >>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
| dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))
|
| Using dictionaries. Two fields named 'gender' and 'age':
|
| >>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
| dtype([('gender', 'S1'), ('age', 'u1')])
|
| Offsets in bytes, here 0 and 25:
|
| >>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)})
| dtype([('surname', 'S25'), ('age', 'u1')])
|
| Methods defined here:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| type
numpy.dtypes
Python Library Documentation: module numpy.dtypes in numpy
NAME
numpy.dtypes
DESCRIPTION
This module is home to specific dtypes related functionality and their classes.
For more general information about dtypes, also see `numpy.dtype` and
:ref:`arrays.dtypes`.
Similar to the builtin ``types`` module, this submodule defines types (classes)
that are not widely used directly.
.. versionadded:: NumPy 1.25
The dtypes module is new in NumPy 1.25. Previously DType classes were
only accessible indirectly.
DType classes
-------------
The following are the classes of the corresponding NumPy dtype instances and
NumPy scalar types. The classes can be used in ``isinstance`` checks and can
also be instantiated or used directly. Direct use of these classes is not
typical, since their scalar counterparts (e.g. ``np.float64``) or strings
like ``"float64"`` can be used.
CLASSES
numpy.dtype(builtins.object)
BoolDType
BytesDType
DateTime64DType
ObjectDType
StrDType
StringDType
TimeDelta64DType
VoidDType
_ComplexAbstractDType(numpy.dtype)
CLongDoubleDType
Complex128DType
Complex64DType
_FloatAbstractDType(numpy.dtype)
Float16DType
Float32DType
Float64DType
LongDoubleDType
_IntegerAbstractDType(numpy.dtype)
Int16DType
Int32DType
Int64DType
Int8DType
IntDType
UInt16DType
UInt32DType
UInt64DType
UInt8DType
UIntDType
class BoolDType(numpy.dtype)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| BoolDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.bool'>
| Boolean type (True or False), stored as a byte.
|
| .. warning::
|
| The :class:`bool` type is not a subclass of the :class:`int_` type
| (the :class:`bool` is not even a number type). This is different
| than Python's default implementation of :class:`bool` as a
| sub-class of :class:`int`.
|
| :Character code: ``'?'``
ByteDType = class Int8DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Int8DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.int8'>
| Signed integer type, compatible with C ``char``.
|
| :Character code: ``'b'``
| :Canonical name: `numpy.byte`
| :Alias on this platform (win32 AMD64): `numpy.int8`: 8-bit signed integer (``-128`` to ``127``).
class BytesDType(numpy.dtype)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| BytesDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.bytes_'>
| A byte string.
|
| When used in arrays, this type strips trailing null bytes.
|
| :Character code: ``'S'``
class CLongDoubleDType(_ComplexAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| CLongDoubleDType
| _ComplexAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.clongdouble'>
| Complex number type composed of two extended-precision floating-point
| numbers.
|
| :Character code: ``'G'``
class Complex128DType(_ComplexAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Complex128DType
| _ComplexAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.complex128'>
| Complex number type composed of two double-precision floating-point
| numbers, compatible with Python :class:`complex`.
|
| :Character code: ``'D'``
| :Canonical name: `numpy.cdouble`
| :Alias on this platform (win32 AMD64): `numpy.complex128`: Complex number type composed of 2 64-bit-precision floating-point numbers.
class Complex64DType(_ComplexAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Complex64DType
| _ComplexAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.complex64'>
| Complex number type composed of two single-precision floating-point
| numbers.
|
| :Character code: ``'F'``
| :Canonical name: `numpy.csingle`
| :Alias on this platform (win32 AMD64): `numpy.complex64`: Complex number type composed of 2 32-bit-precision floating-point numbers.
class DateTime64DType(numpy.dtype)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| DateTime64DType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.datetime64'>
| If created from a 64-bit integer, it represents an offset from
| ``1970-01-01T00:00:00``.
| If created from string, the string can be in ISO 8601 date
| or datetime format.
|
| When parsing a string to create a datetime object, if the string contains
| a trailing timezone (A 'Z' or a timezone offset), the timezone will be
| dropped and a User Warning is given.
|
| Datetime64 objects should be considered to be UTC and therefore have an
| offset of +0000.
|
| >>> np.datetime64(10, 'Y')
| np.datetime64('1980')
| >>> np.datetime64('1980', 'Y')
| np.datetime64('1980')
| >>> np.datetime64(10, 'D')
| np.datetime64('1970-01-11')
|
| See :ref:`arrays.datetime` for more information.
|
| :Character code: ``'M'``
class Float16DType(_FloatAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Float16DType
| _FloatAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.float16'>
| Half-precision floating-point number type.
|
| :Character code: ``'e'``
| :Canonical name: `numpy.half`
| :Alias on this platform (win32 AMD64): `numpy.float16`: 16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa.
class Float32DType(_FloatAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Float32DType
| _FloatAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.float32'>
| Single-precision floating-point number type, compatible with C ``float``.
|
| :Character code: ``'f'``
| :Canonical name: `numpy.single`
| :Alias on this platform (win32 AMD64): `numpy.float32`: 32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa.
class Float64DType(_FloatAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Float64DType
| _FloatAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.float64'>
| Double-precision floating-point number type, compatible with Python
| :class:`float` and C ``double``.
|
| :Character code: ``'d'``
| :Canonical name: `numpy.double`
| :Alias on this platform (win32 AMD64): `numpy.float64`: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa.
class Int16DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Int16DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.int16'>
| Signed integer type, compatible with C ``short``.
|
| :Character code: ``'h'``
| :Canonical name: `numpy.short`
| :Alias on this platform (win32 AMD64): `numpy.int16`: 16-bit signed integer (``-32_768`` to ``32_767``).
class Int32DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Int32DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.int32'>
class Int64DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Int64DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.int64'>
| Default signed integer type, 64bit on 64bit systems and 32bit on 32bit
| systems.
|
| :Character code: ``'q'``
| :Canonical name: `numpy.int_`
| :Alias on this platform (win32 AMD64): `numpy.int64`: 64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``).
| :Alias on this platform (win32 AMD64): `numpy.intp`: Signed integer large enough to fit pointer, compatible with C ``intptr_t``.
class Int8DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Int8DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.int8'>
| Signed integer type, compatible with C ``char``.
|
| :Character code: ``'b'``
| :Canonical name: `numpy.byte`
| :Alias on this platform (win32 AMD64): `numpy.int8`: 8-bit signed integer (``-128`` to ``127``).
class IntDType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| IntDType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.intc'>
| Signed integer type, compatible with C ``int``.
|
| :Character code: ``'i'``
LongDType = class Int32DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Int32DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.int32'>
class LongDoubleDType(_FloatAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| LongDoubleDType
| _FloatAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.longdouble'>
| Extended-precision floating-point number type, compatible with C
| ``long double`` but not necessarily with IEEE 754 quadruple-precision.
|
| :Character code: ``'g'``
LongLongDType = class Int64DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Int64DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.int64'>
| Default signed integer type, 64bit on 64bit systems and 32bit on 32bit
| systems.
|
| :Character code: ``'q'``
| :Canonical name: `numpy.int_`
| :Alias on this platform (win32 AMD64): `numpy.int64`: 64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``).
| :Alias on this platform (win32 AMD64): `numpy.intp`: Signed integer large enough to fit pointer, compatible with C ``intptr_t``.
class ObjectDType(numpy.dtype)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| ObjectDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.object_'>
| Any Python object.
|
| :Character code: ``'O'``
ShortDType = class Int16DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| Int16DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.int16'>
| Signed integer type, compatible with C ``short``.
|
| :Character code: ``'h'``
| :Canonical name: `numpy.short`
| :Alias on this platform (win32 AMD64): `numpy.int16`: 16-bit signed integer (``-32_768`` to ``32_767``).
class StrDType(numpy.dtype)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| StrDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.str_'>
| A unicode string.
|
| This type strips trailing null codepoints.
|
| >>> s = np.str_("abc\x00")
| >>> s
| 'abc'
|
| Unlike the builtin :class:`str`, this supports the
| :ref:`python:bufferobjects`, exposing its contents as UCS4:
|
| >>> m = memoryview(np.str_("abc"))
| >>> m.format
| '3w'
| >>> m.tobytes()
| b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'
|
| :Character code: ``'U'``
class StringDType(numpy.dtype)
| StringDType(*, na_object=np._NoValue, coerce=True)
|
| Create a StringDType instance.
|
| StringDType can be used to store UTF-8 encoded variable-width strings in
| a NumPy array.
|
| Parameters
| ----------
| na_object : object, optional
| Object used to represent missing data. If unset, the array will not
| use a missing data sentinel.
| coerce : bool, optional
| Whether or not items in an array-like passed to an array creation
| function that are neither a str or str subtype should be coerced to
| str. Defaults to True. If set to False, creating a StringDType
| array from an array-like containing entries that are not already
| strings will raise an error.
|
| Examples
| --------
|
| >>> import numpy as np
|
| >>> from numpy.dtypes import StringDType
| >>> np.array(["hello", "world"], dtype=StringDType())
| array(["hello", "world"], dtype=StringDType())
|
| >>> arr = np.array(["hello", None, "world"],
| ... dtype=StringDType(na_object=None))
| >>> arr
| array(["hello", None, "world"], dtype=StringDType(na_object=None))
| >>> arr[1] is None
| True
|
| >>> arr = np.array(["hello", np.nan, "world"],
| ... dtype=StringDType(na_object=np.nan))
| >>> np.isnan(arr)
| array([False, True, False])
|
| >>> np.array([1.2, object(), "hello world"],
| ... dtype=StringDType(coerce=True))
| ValueError: StringDType only allows string data when string coercion
| is disabled.
|
| >>> np.array(["hello", "world"], dtype=StringDType(coerce=True))
| array(["hello", "world"], dtype=StringDType(coerce=True))
|
| Method resolution order:
| StringDType
| numpy.dtype
| builtins.object
|
| Methods defined here:
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Reduction method for a StringDType object
|
| __repr__(self, /)
| Return repr(self).
|
| __str__(self, /)
| Return str(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| coerce
| Controls hether non-string values should be coerced to string
|
| na_object
| The missing value object associated with the dtype instance
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __getitem__(self, key, /)
| Return self[key].
|
| __len__(self, /)
| Return len(self).
|
| __mul__(self, value, /)
| Return self*value.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'str'>
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
class TimeDelta64DType(numpy.dtype)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| TimeDelta64DType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.timedelta64'>
| A timedelta stored as a 64-bit integer.
|
| See :ref:`arrays.datetime` for more information.
|
| :Character code: ``'m'``
UByteDType = class UInt8DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| UInt8DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.uint8'>
| Unsigned integer type, compatible with C ``unsigned char``.
|
| :Character code: ``'B'``
| :Canonical name: `numpy.ubyte`
| :Alias on this platform (win32 AMD64): `numpy.uint8`: 8-bit unsigned integer (``0`` to ``255``).
class UInt16DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| UInt16DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.uint16'>
| Unsigned integer type, compatible with C ``unsigned short``.
|
| :Character code: ``'H'``
| :Canonical name: `numpy.ushort`
| :Alias on this platform (win32 AMD64): `numpy.uint16`: 16-bit unsigned integer (``0`` to ``65_535``).
class UInt32DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| UInt32DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.uint32'>
class UInt64DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| UInt64DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.uint64'>
| Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit
| systems.
|
| :Character code: ``'Q'``
| :Canonical name: `numpy.uint`
| :Alias on this platform (win32 AMD64): `numpy.uint64`: 64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``).
| :Alias on this platform (win32 AMD64): `numpy.uintp`: Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``.
class UInt8DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| UInt8DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.uint8'>
| Unsigned integer type, compatible with C ``unsigned char``.
|
| :Character code: ``'B'``
| :Canonical name: `numpy.ubyte`
| :Alias on this platform (win32 AMD64): `numpy.uint8`: 8-bit unsigned integer (``0`` to ``255``).
class UIntDType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| UIntDType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.uintc'>
| Unsigned integer type, compatible with C ``unsigned int``.
|
| :Character code: ``'I'``
ULongDType = class UInt32DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| UInt32DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.uint32'>
ULongLongDType = class UInt64DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| UInt64DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.uint64'>
| Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit
| systems.
|
| :Character code: ``'Q'``
| :Canonical name: `numpy.uint`
| :Alias on this platform (win32 AMD64): `numpy.uint64`: 64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``).
| :Alias on this platform (win32 AMD64): `numpy.uintp`: Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``.
UShortDType = class UInt16DType(_IntegerAbstractDType)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| UInt16DType
| _IntegerAbstractDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.uint16'>
| Unsigned integer type, compatible with C ``unsigned short``.
|
| :Character code: ``'H'``
| :Canonical name: `numpy.ushort`
| :Alias on this platform (win32 AMD64): `numpy.uint16`: 16-bit unsigned integer (``0`` to ``65_535``).
class VoidDType(numpy.dtype)
| DType class corresponding to the scalar type and dtype of the same name.
|
| Please see `numpy.dtype` for the typical way to create
| dtype instances and :ref:`arrays.dtypes` for additional
| information.
|
| Method resolution order:
| VoidDType
| numpy.dtype
| builtins.object
|
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.dtype:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| newbyteorder(...)
| newbyteorder(new_order='S', /)
|
| Return a new dtype with a different byte order.
|
| Changes are also made in all fields and sub-arrays of the data type.
|
| Parameters
| ----------
| new_order : string, optional
| Byte order to force; a value from the byte order specifications
| below. The default value ('S') results in swapping the current
| byte order. `new_order` codes can be any of:
|
| * 'S' - swap dtype from current to opposite endian
| * {'<', 'little'} - little endian
| * {'>', 'big'} - big endian
| * {'=', 'native'} - native order
| * {'|', 'I'} - ignore (no change to byte order)
|
| Returns
| -------
| new_dtype : dtype
| New dtype object with the given change to the byte order.
|
| Notes
| -----
| Changes are also made in all fields and sub-arrays of the data type.
|
| Examples
| --------
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> import numpy as np
| >>> native_dt = np.dtype(native_code+'i2')
| >>> swapped_dt = np.dtype(swapped_code+'i2')
| >>> native_dt.newbyteorder('S') == swapped_dt
| True
| >>> native_dt.newbyteorder() == swapped_dt
| True
| >>> native_dt == swapped_dt.newbyteorder('S')
| True
| >>> native_dt == swapped_dt.newbyteorder('=')
| True
| >>> native_dt == swapped_dt.newbyteorder('N')
| True
| >>> native_dt == native_dt.newbyteorder('|')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('<')
| True
| >>> np.dtype('<i2') == native_dt.newbyteorder('L')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('>')
| True
| >>> np.dtype('>i2') == native_dt.newbyteorder('B')
| True
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.dtype:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.dtype` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.dtype` type.
|
| Examples
| --------
| >>> import numpy as np
|
| >>> np.dtype[np.int64]
| numpy.dtype[numpy.int64]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.dtype:
|
| alignment
| The required alignment (bytes) of this data-type according to the compiler.
|
| More information is available in the C-API section of the manual.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype('i4')
| >>> x.alignment
| 4
|
| >>> x = np.dtype(float)
| >>> x.alignment
| 8
|
| base
| Returns dtype for the base element of the subarrays,
| regardless of their dimension or shape.
|
| See Also
| --------
| dtype.subdtype
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.base
| dtype('float32')
|
| >>> x = numpy.dtype('i2')
| >>> x.base
| dtype('int16')
|
| byteorder
| A character indicating the byte-order of this data-type object.
|
| One of:
|
| === ==============
| '=' native
| '<' little-endian
| '>' big-endian
| '|' not applicable
| === ==============
|
| All built-in data-type objects have byteorder either '=' or '|'.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.byteorder
| '='
| >>> # endian is not relevant for 8 bit numbers
| >>> np.dtype('i1').byteorder
| '|'
| >>> # or ASCII strings
| >>> np.dtype('S2').byteorder
| '|'
| >>> # Even if specific code is given, and it is native
| >>> # '=' is the byteorder
| >>> import sys
| >>> sys_is_le = sys.byteorder == 'little'
| >>> native_code = '<' if sys_is_le else '>'
| >>> swapped_code = '>' if sys_is_le else '<'
| >>> dt = np.dtype(native_code + 'i2')
| >>> dt.byteorder
| '='
| >>> # Swapped code shows up as itself
| >>> dt = np.dtype(swapped_code + 'i2')
| >>> dt.byteorder == swapped_code
| True
|
| char
| A unique character code for each of the 21 different built-in types.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.char
| 'd'
|
| descr
| `__array_interface__` description of the data-type.
|
| The format is that required by the 'descr' key in the
| `__array_interface__` attribute.
|
| Warning: This attribute exists specifically for `__array_interface__`,
| and passing it directly to `numpy.dtype` will not accurately reconstruct
| some dtypes (e.g., scalar and subarray dtypes).
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.descr
| [('', '<f8')]
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.descr
| [('name', '<U16'), ('grades', '<f8', (2,))]
|
| fields
| Dictionary of named fields defined for this data type, or ``None``.
|
| The dictionary is indexed by keys that are the names of the fields.
| Each entry in the dictionary is a tuple fully describing the field::
|
| (dtype, offset[, title])
|
| Offset is limited to C int, which is signed and usually 32 bits.
| If present, the optional title can be any object (if it is a string
| or unicode then it will also be a key in the fields dictionary,
| otherwise it's meta-data). Notice also that the first two elements
| of the tuple can be passed directly as arguments to the
| ``ndarray.getfield`` and ``ndarray.setfield`` methods.
|
| See Also
| --------
| ndarray.getfield, ndarray.setfield
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> print(dt.fields)
| {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
|
| flags
| Bit-flags describing how this data type is to be interpreted.
|
| Bit-masks are in ``numpy._core.multiarray`` as the constants
| `ITEM_HASOBJECT`, `LIST_PICKLE`, `ITEM_IS_POINTER`, `NEEDS_INIT`,
| `NEEDS_PYAPI`, `USE_GETITEM`, `USE_SETITEM`. A full explanation
| of these flags is in C-API documentation; they are largely useful
| for user-defined data-types.
|
| The following example demonstrates that operations on this particular
| dtype requires Python C-API.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.flags
| 16
| >>> np._core.multiarray.NEEDS_PYAPI
| 16
|
| hasobject
| Boolean indicating whether this dtype contains any reference-counted
| objects in any fields or sub-dtypes.
|
| Recall that what is actually in the ndarray memory representing
| the Python object is the memory address of that object (a pointer).
| Special handling may be required, and this attribute is useful for
| distinguishing data types that may contain arbitrary Python objects
| and data-types that won't.
|
| isalignedstruct
| Boolean indicating whether the dtype is a struct which maintains
| field alignment. This flag is sticky, so when combining multiple
| structs together, it is preserved and produces new dtypes which
| are also aligned.
|
| isbuiltin
| Integer indicating how this dtype relates to the built-in dtypes.
|
| Read-only.
|
| = ========================================================================
| 0 if this is a structured array type, with fields
| 1 if this is a dtype compiled into numpy (such as ints, floats etc)
| 2 if the dtype is for a user-defined numpy type
| A user-defined type uses the numpy C-API machinery to extend
| numpy to handle a new array type. See
| :ref:`user.user-defined-data-types` in the NumPy manual.
| = ========================================================================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i2')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype('f8')
| >>> dt.isbuiltin
| 1
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.isbuiltin
| 0
|
| isnative
| Boolean indicating whether the byte order of this dtype is native
| to the platform.
|
| itemsize
| The element size of this data-type object.
|
| For 18 of the 21 types this number is fixed by the data-type.
| For the flexible data-types, this number can be anything.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> arr = np.array([[1, 2], [3, 4]])
| >>> arr.dtype
| dtype('int64')
| >>> arr.itemsize
| 8
|
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.itemsize
| 80
|
| kind
| A character code (one of 'biufcmMOSUV') identifying the general kind of data.
|
| = ======================
| b boolean
| i signed integer
| u unsigned integer
| f floating-point
| c complex floating-point
| m timedelta
| M datetime
| O object
| S (byte-)string
| U Unicode
| V void
| = ======================
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype('i4')
| >>> dt.kind
| 'i'
| >>> dt = np.dtype('f8')
| >>> dt.kind
| 'f'
| >>> dt = np.dtype([('field1', 'f8')])
| >>> dt.kind
| 'V'
|
| metadata
| Either ``None`` or a readonly dictionary of metadata (mappingproxy).
|
| The metadata field can be set using any dictionary at data-type
| creation. NumPy currently has no uniform approach to propagating
| metadata; although some array operations preserve it, there is no
| guarantee that others will.
|
| .. warning::
|
| Although used in certain projects, this feature was long undocumented
| and is not well supported. Some aspects of metadata propagation
| are expected to change in the future.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(float, metadata={"key": "value"})
| >>> dt.metadata["key"]
| 'value'
| >>> arr = np.array([1, 2, 3], dtype=dt)
| >>> arr.dtype.metadata
| mappingproxy({'key': 'value'})
|
| Adding arrays with identical datatypes currently preserves the metadata:
|
| >>> (arr + arr).dtype.metadata
| mappingproxy({'key': 'value'})
|
| But if the arrays have different dtype metadata, the metadata may be
| dropped:
|
| >>> dt2 = np.dtype(float, metadata={"key2": "value2"})
| >>> arr2 = np.array([3, 2, 1], dtype=dt2)
| >>> (arr + arr2).dtype.metadata is None
| True # The metadata field is cleared so None is returned
|
| name
| A bit-width name for this data-type.
|
| Un-sized flexible data-type objects do not have this attribute.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.name
| 'float64'
| >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)])
| >>> x.name
| 'void640'
|
| names
| Ordered list of field names, or ``None`` if there are no fields.
|
| The names are ordered according to increasing byte offset. This can be
| used, for example, to walk through all of the named fields in offset order.
|
| Examples
| --------
| >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
| >>> dt.names
| ('name', 'grades')
|
| ndim
| Number of dimensions of the sub-array if this data type describes a
| sub-array, and ``0`` otherwise.
|
| .. versionadded:: 1.13.0
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.dtype(float)
| >>> x.ndim
| 0
|
| >>> x = np.dtype((float, 8))
| >>> x.ndim
| 1
|
| >>> x = np.dtype(('i4', (3, 4)))
| >>> x.ndim
| 2
|
| num
| A unique number for each of the 21 different built-in types.
|
| These are roughly ordered from least-to-most precision.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(str)
| >>> dt.num
| 19
|
| >>> dt = np.dtype(float)
| >>> dt.num
| 12
|
| shape
| Shape tuple of the sub-array if this data type describes a sub-array,
| and ``()`` otherwise.
|
| Examples
| --------
|
| >>> import numpy as np
| >>> dt = np.dtype(('i4', 4))
| >>> dt.shape
| (4,)
|
| >>> dt = np.dtype(('i4', (2, 3)))
| >>> dt.shape
| (2, 3)
|
| str
| The array-protocol typestring of this data-type object.
|
| subdtype
| Tuple ``(item_dtype, shape)`` if this `dtype` describes a sub-array, and
| None otherwise.
|
| The *shape* is the fixed shape of the sub-array described by this
| data type, and *item_dtype* the data type of the array.
|
| If a field whose dtype object has this attribute is retrieved,
| then the extra dimensions implied by *shape* are tacked on to
| the end of the retrieved array.
|
| See Also
| --------
| dtype.base
|
| Examples
| --------
| >>> import numpy as np
| >>> x = numpy.dtype('8f')
| >>> x.subdtype
| (dtype('float32'), (8,))
|
| >>> x = numpy.dtype('i2')
| >>> x.subdtype
| >>>
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.dtype:
|
| type = <class 'numpy.void'>
| np.void(length_or_data, /, dtype=None)
|
| Create a new structured or unstructured void scalar.
|
| Parameters
| ----------
| length_or_data : int, array-like, bytes-like, object
| One of multiple meanings (see notes). The length or
| bytes data of an unstructured void. Or alternatively,
| the data to be stored in the new scalar when `dtype`
| is provided.
| This can be an array-like, in which case an array may
| be returned.
| dtype : dtype, optional
| If provided the dtype of the new scalar. This dtype must
| be "void" dtype (i.e. a structured or unstructured void,
| see also :ref:`defining-structured-types`).
|
| .. versionadded:: 1.24
|
| Notes
| -----
| For historical reasons and because void scalars can represent both
| arbitrary byte data and structured dtypes, the void constructor
| has three calling conventions:
|
| 1. ``np.void(5)`` creates a ``dtype="V5"`` scalar filled with five
| ``\0`` bytes. The 5 can be a Python or NumPy integer.
| 2. ``np.void(b"bytes-like")`` creates a void scalar from the byte string.
| The dtype itemsize will match the byte string length, here ``"V10"``.
| 3. When a ``dtype=`` is passed the call is roughly the same as an
| array creation. However, a void scalar rather than array is returned.
|
| Please see the examples which show all three different conventions.
|
| Examples
| --------
| >>> np.void(5)
| np.void(b'\x00\x00\x00\x00\x00')
| >>> np.void(b'abcd')
| np.void(b'\x61\x62\x63\x64')
| >>> np.void((3.2, b'eggs'), dtype="d,S5")
| np.void((3.2, b'eggs'), dtype=[('f0', '<f8'), ('f1', 'S5')])
| >>> np.void(3, dtype=[('x', np.int8), ('y', np.int8)])
| np.void((3, 3), dtype=[('x', 'i1'), ('y', 'i1')])
|
| :Character code: ``'V'``
DATA
__all__ = ['BoolDType', 'Int8DType', 'ByteDType', 'UInt8DType', 'UByte...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\dtypes.py
numpy.e
Python Library Documentation: float object
class float(object)
| float(x=0, /)
|
| Convert a string or number to a floating-point number, if possible.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(self, /)
| Return the ceiling as an Integral.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(self, /)
| Return the floor as an Integral.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Formats the float according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __round__(self, ndigits=None, /)
| Return the Integral closest to x, rounding half toward even.
|
| When an argument is passed, work like built-in round(x, ndigits).
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| as_integer_ratio(self, /)
| Return a pair of integers, whose ratio is exactly equal to the original float.
|
| The ratio is in lowest terms and has a positive denominator. Raise
| OverflowError on infinities and a ValueError on NaNs.
|
| >>> (10.0).as_integer_ratio()
| (10, 1)
| >>> (0.0).as_integer_ratio()
| (0, 1)
| >>> (-.25).as_integer_ratio()
| (-1, 4)
|
| conjugate(self, /)
| Return self, the complex conjugate of any float.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> 3.14159.hex()
| '0x1.921f9f01b866ep+1'
|
| is_integer(self, /)
| Return True if the float is an integer.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __getformat__(typestr, /)
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
| little-endian' best describes the format of floating-point numbers used by the
| C type named by typestr.
|
| fromhex(string, /)
| Create a floating-point number from a hexadecimal string.
|
| >>> float.fromhex('0x1.ffffp10')
| 2047.984375
| >>> float.fromhex('-0x1p-1074')
| -5e-324
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| imag
| the imaginary part of a complex number
|
| real
| the real part of a complex number
numpy.ediff1d
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
ediff1d(ary, to_end=None, to_begin=None)
The differences between consecutive elements of an array.
Parameters
----------
ary : array_like
If necessary, will be flattened before the differences are taken.
to_end : array_like, optional
Number(s) to append at the end of the returned differences.
to_begin : array_like, optional
Number(s) to prepend at the beginning of the returned differences.
Returns
-------
ediff1d : ndarray
The differences. Loosely, this is ``ary.flat[1:] - ary.flat[:-1]``.
See Also
--------
diff, gradient
Notes
-----
When applied to masked arrays, this function drops the mask information
if the `to_begin` and/or `to_end` parameters are used.
Examples
--------
>>> import numpy as np
>>> x = np.array([1, 2, 4, 7, 0])
>>> np.ediff1d(x)
array([ 1, 2, 3, -7])
>>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99]))
array([-99, 1, 2, ..., -7, 88, 99])
The returned array is always 1D.
>>> y = [[1, 2, 4], [1, 6, 24]]
>>> np.ediff1d(y)
array([ 1, 2, -3, 5, 18])
numpy.einsum
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
einsum(*operands, out=None, optimize=False, **kwargs)
einsum(subscripts, *operands, out=None, dtype=None, order='K',
casting='safe', optimize=False)
Evaluates the Einstein summation convention on the operands.
Using the Einstein summation convention, many common multi-dimensional,
linear algebraic array operations can be represented in a simple fashion.
In *implicit* mode `einsum` computes these values.
In *explicit* mode, `einsum` provides further flexibility to compute
other array operations that might not be considered classical Einstein
summation operations, by disabling, or forcing summation over specified
subscript labels.
See the notes and examples for clarification.
Parameters
----------
subscripts : str
Specifies the subscripts for summation as comma separated list of
subscript labels. An implicit (classical Einstein summation)
calculation is performed unless the explicit indicator '->' is
included as well as subscript labels of the precise output form.
operands : list of array_like
These are the arrays for the operation.
out : ndarray, optional
If provided, the calculation is done into this array.
dtype : {data-type, None}, optional
If provided, forces the calculation to use the data type specified.
Note that you may have to also give a more liberal `casting`
parameter to allow the conversions. Default is None.
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout of the output. 'C' means it should
be C contiguous. 'F' means it should be Fortran contiguous,
'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
'K' means it should be as close to the layout as the inputs as
is possible, including arbitrarily permuted axes.
Default is 'K'.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Setting this to
'unsafe' is not recommended, as it can adversely affect accumulations.
* 'no' means the data types should not be cast at all.
* 'equiv' means only byte-order changes are allowed.
* 'safe' means only casts which can preserve values are allowed.
* 'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
* 'unsafe' means any data conversions may be done.
Default is 'safe'.
optimize : {False, True, 'greedy', 'optimal'}, optional
Controls if intermediate optimization should occur. No optimization
will occur if False and True will default to the 'greedy' algorithm.
Also accepts an explicit contraction list from the ``np.einsum_path``
function. See ``np.einsum_path`` for more details. Defaults to False.
Returns
-------
output : ndarray
The calculation based on the Einstein summation convention.
See Also
--------
einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
einsum:
Similar verbose interface is provided by the
`einops <https://github.com/arogozhnikov/einops>`_ package to cover
additional operations: transpose, reshape/flatten, repeat/tile,
squeeze/unsqueeze and reductions.
The `opt_einsum <https://optimized-einsum.readthedocs.io/en/stable/>`_
optimizes contraction order for einsum-like expressions
in backend-agnostic manner.
Notes
-----
.. versionadded:: 1.6.0
The Einstein summation convention can be used to compute
many multi-dimensional, linear algebraic array operations. `einsum`
provides a succinct way of representing these.
A non-exhaustive list of these operations,
which can be computed by `einsum`, is shown below along with examples:
* Trace of an array, :py:func:`numpy.trace`.
* Return a diagonal, :py:func:`numpy.diag`.
* Array axis summations, :py:func:`numpy.sum`.
* Transpositions and permutations, :py:func:`numpy.transpose`.
* Matrix multiplication and dot product, :py:func:`numpy.matmul`
:py:func:`numpy.dot`.
* Vector inner and outer products, :py:func:`numpy.inner`
:py:func:`numpy.outer`.
* Broadcasting, element-wise and scalar multiplication,
:py:func:`numpy.multiply`.
* Tensor contractions, :py:func:`numpy.tensordot`.
* Chained array operations, in efficient calculation order,
:py:func:`numpy.einsum_path`.
The subscripts string is a comma-separated list of subscript labels,
where each label refers to a dimension of the corresponding operand.
Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label
appears only once, it is not summed, so ``np.einsum('i', a)``
produces a view of ``a`` with no changes. A further example
``np.einsum('ij,jk', a, b)`` describes traditional matrix multiplication
and is equivalent to :py:func:`np.matmul(a,b) <numpy.matmul>`.
Repeated subscript labels in one operand take the diagonal.
For example, ``np.einsum('ii', a)`` is equivalent to
:py:func:`np.trace(a) <numpy.trace>`.
In *implicit mode*, the chosen subscripts are important
since the axes of the output are reordered alphabetically. This
means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
``np.einsum('ji', a)`` takes its transpose. Additionally,
``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
``np.einsum('ij,jh', a, b)`` returns the transpose of the
multiplication since subscript 'h' precedes subscript 'i'.
In *explicit mode* the output can be directly controlled by
specifying output subscript labels. This requires the
identifier '->' as well as the list of output subscript labels.
This feature increases the flexibility of the function since
summing can be disabled or forced when required. The call
``np.einsum('i->', a)`` is like :py:func:`np.sum(a) <numpy.sum>`
if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``
is like :py:func:`np.diag(a) <numpy.diag>` if ``a`` is a square 2-D array.
The difference is that `einsum` does not allow broadcasting by default.
Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
order of the output subscript labels and therefore returns matrix
multiplication, unlike the example above in implicit mode.
To enable and control broadcasting, use an ellipsis. Default
NumPy-style broadcasting is done by adding an ellipsis
to the left of each term, like ``np.einsum('...ii->...i', a)``.
``np.einsum('...i->...', a)`` is like
:py:func:`np.sum(a, axis=-1) <numpy.sum>` for array ``a`` of any shape.
To take the trace along the first and last axes,
you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
product with the left-most indices instead of rightmost, one can do
``np.einsum('ij...,jk...->ik...', a, b)``.
When there is only one operand, no axes are summed, and no output
parameter is provided, a view into the operand is returned instead
of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)``
produces a view (changed in version 1.10.0).
`einsum` also provides an alternative way to provide the subscripts and
operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
If the output shape is not provided in this format `einsum` will be
calculated in implicit mode, otherwise it will be performed explicitly.
The examples below have corresponding `einsum` calls with the two
parameter methods.
.. versionadded:: 1.10.0
Views returned from einsum are now writeable whenever the input array
is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>`
and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
of a 2D array.
.. versionadded:: 1.12.0
Added the ``optimize`` argument which will optimize the contraction order
of an einsum expression. For a contraction with three or more operands
this can greatly increase the computational efficiency at the cost of
a larger memory footprint during computation.
Typically a 'greedy' algorithm is applied which empirical tests have shown
returns the optimal path in the majority of cases. In some cases 'optimal'
will return the superlative path through a more expensive, exhaustive
search. For iterative calculations it may be advisable to calculate
the optimal path once and reuse that path by supplying it as an argument.
An example is given below.
See :py:func:`numpy.einsum_path` for more details.
Examples
--------
>>> a = np.arange(25).reshape(5,5)
>>> b = np.arange(5)
>>> c = np.arange(6).reshape(2,3)
Trace of a matrix:
>>> np.einsum('ii', a)
60
>>> np.einsum(a, [0,0])
60
>>> np.trace(a)
60
Extract the diagonal (requires explicit form):
>>> np.einsum('ii->i', a)
array([ 0, 6, 12, 18, 24])
>>> np.einsum(a, [0,0], [0])
array([ 0, 6, 12, 18, 24])
>>> np.diag(a)
array([ 0, 6, 12, 18, 24])
Sum over an axis (requires explicit form):
>>> np.einsum('ij->i', a)
array([ 10, 35, 60, 85, 110])
>>> np.einsum(a, [0,1], [0])
array([ 10, 35, 60, 85, 110])
>>> np.sum(a, axis=1)
array([ 10, 35, 60, 85, 110])
For higher dimensional arrays summing a single axis can be done
with ellipsis:
>>> np.einsum('...j->...', a)
array([ 10, 35, 60, 85, 110])
>>> np.einsum(a, [Ellipsis,1], [Ellipsis])
array([ 10, 35, 60, 85, 110])
Compute a matrix transpose, or reorder any number of axes:
>>> np.einsum('ji', c)
array([[0, 3],
[1, 4],
[2, 5]])
>>> np.einsum('ij->ji', c)
array([[0, 3],
[1, 4],
[2, 5]])
>>> np.einsum(c, [1,0])
array([[0, 3],
[1, 4],
[2, 5]])
>>> np.transpose(c)
array([[0, 3],
[1, 4],
[2, 5]])
Vector inner products:
>>> np.einsum('i,i', b, b)
30
>>> np.einsum(b, [0], b, [0])
30
>>> np.inner(b,b)
30
Matrix vector multiplication:
>>> np.einsum('ij,j', a, b)
array([ 30, 80, 130, 180, 230])
>>> np.einsum(a, [0,1], b, [1])
array([ 30, 80, 130, 180, 230])
>>> np.dot(a, b)
array([ 30, 80, 130, 180, 230])
>>> np.einsum('...j,j', a, b)
array([ 30, 80, 130, 180, 230])
Broadcasting and scalar multiplication:
>>> np.einsum('..., ...', 3, c)
array([[ 0, 3, 6],
[ 9, 12, 15]])
>>> np.einsum(',ij', 3, c)
array([[ 0, 3, 6],
[ 9, 12, 15]])
>>> np.einsum(3, [Ellipsis], c, [Ellipsis])
array([[ 0, 3, 6],
[ 9, 12, 15]])
>>> np.multiply(3, c)
array([[ 0, 3, 6],
[ 9, 12, 15]])
Vector outer product:
>>> np.einsum('i,j', np.arange(2)+1, b)
array([[0, 1, 2, 3, 4],
[0, 2, 4, 6, 8]])
>>> np.einsum(np.arange(2)+1, [0], b, [1])
array([[0, 1, 2, 3, 4],
[0, 2, 4, 6, 8]])
>>> np.outer(np.arange(2)+1, b)
array([[0, 1, 2, 3, 4],
[0, 2, 4, 6, 8]])
Tensor contraction:
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> np.einsum('ijk,jil->kl', a, b)
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])
>>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])
>>> np.tensordot(a,b, axes=([1,0],[0,1]))
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])
Writeable returned arrays (since version 1.10.0):
>>> a = np.zeros((3, 3))
>>> np.einsum('ii->i', a)[:] = 1
>>> a
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
Example of ellipsis use:
>>> a = np.arange(6).reshape((3,2))
>>> b = np.arange(12).reshape((4,3))
>>> np.einsum('ki,jk->ij', a, b)
array([[10, 28, 46, 64],
[13, 40, 67, 94]])
>>> np.einsum('ki,...k->i...', a, b)
array([[10, 28, 46, 64],
[13, 40, 67, 94]])
>>> np.einsum('k...,jk', a, b)
array([[10, 28, 46, 64],
[13, 40, 67, 94]])
Chained array operations. For more complicated contractions, speed ups
might be achieved by repeatedly computing a 'greedy' path or pre-computing
the 'optimal' path and repeatedly applying it, using an `einsum_path`
insertion (since version 1.12.0). Performance improvements can be
particularly significant with larger arrays:
>>> a = np.ones(64).reshape(2,4,8)
Basic `einsum`: ~1520ms (benchmarked on 3.1GHz Intel i5.)
>>> for iteration in range(500):
... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
Sub-optimal `einsum` (due to repeated path calculation time): ~330ms
>>> for iteration in range(500):
... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
... optimize='optimal')
Greedy `einsum` (faster optimal path approximation): ~160ms
>>> for iteration in range(500):
... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy')
Optimal `einsum` (best usage pattern in some use cases): ~110ms
>>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
... optimize='optimal')[0]
>>> for iteration in range(500):
... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=path)
numpy.einsum_path
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
einsum_path(*operands, optimize='greedy', einsum_call=False)
einsum_path(subscripts, *operands, optimize='greedy')
Evaluates the lowest cost contraction order for an einsum expression by
considering the creation of intermediate arrays.
Parameters
----------
subscripts : str
Specifies the subscripts for summation.
*operands : list of array_like
These are the arrays for the operation.
optimize : {bool, list, tuple, 'greedy', 'optimal'}
Choose the type of path. If a tuple is provided, the second argument is
assumed to be the maximum intermediate size created. If only a single
argument is provided the largest input or output array size is used
as a maximum intermediate size.
* if a list is given that starts with ``einsum_path``, uses this as the
contraction path
* if False no optimization is taken
* if True defaults to the 'greedy' algorithm
* 'optimal' An algorithm that combinatorially explores all possible
ways of contracting the listed tensors and chooses the least costly
path. Scales exponentially with the number of terms in the
contraction.
* 'greedy' An algorithm that chooses the best pair contraction
at each step. Effectively, this algorithm searches the largest inner,
Hadamard, and then outer products at each step. Scales cubically with
the number of terms in the contraction. Equivalent to the 'optimal'
path for most contractions.
Default is 'greedy'.
Returns
-------
path : list of tuples
A list representation of the einsum path.
string_repr : str
A printable representation of the einsum path.
Notes
-----
The resulting path indicates which terms of the input contraction should be
contracted first, the result of this contraction is then appended to the
end of the contraction list. This list can then be iterated over until all
intermediate contractions are complete.
See Also
--------
einsum, linalg.multi_dot
Examples
--------
We can begin with a chain dot example. In this case, it is optimal to
contract the ``b`` and ``c`` tensors first as represented by the first
element of the path ``(1, 2)``. The resulting tensor is added to the end
of the contraction and the remaining contraction ``(0, 1)`` is then
completed.
>>> np.random.seed(123)
>>> a = np.random.rand(2, 2)
>>> b = np.random.rand(2, 5)
>>> c = np.random.rand(5, 2)
>>> path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy')
>>> print(path_info[0])
['einsum_path', (1, 2), (0, 1)]
>>> print(path_info[1])
Complete contraction: ij,jk,kl->il # may vary
Naive scaling: 4
Optimized scaling: 3
Naive FLOP count: 1.600e+02
Optimized FLOP count: 5.600e+01
Theoretical speedup: 2.857
Largest intermediate: 4.000e+00 elements
-------------------------------------------------------------------------
scaling current remaining
-------------------------------------------------------------------------
3 kl,jk->jl ij,jl->il
3 jl,ij->il il->il
A more complex index transformation example.
>>> I = np.random.rand(10, 10, 10, 10)
>>> C = np.random.rand(10, 10)
>>> path_info = np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C,
... optimize='greedy')
>>> print(path_info[0])
['einsum_path', (0, 2), (0, 3), (0, 2), (0, 1)]
>>> print(path_info[1])
Complete contraction: ea,fb,abcd,gc,hd->efgh # may vary
Naive scaling: 8
Optimized scaling: 5
Naive FLOP count: 8.000e+08
Optimized FLOP count: 8.000e+05
Theoretical speedup: 1000.000
Largest intermediate: 1.000e+04 elements
--------------------------------------------------------------------------
scaling current remaining
--------------------------------------------------------------------------
5 abcd,ea->bcde fb,gc,hd,bcde->efgh
5 bcde,fb->cdef gc,hd,cdef->efgh
5 cdef,gc->defg hd,defg->efgh
5 defg,hd->efgh efgh->efgh
numpy.emath
Python Library Documentation: module numpy.lib.scimath in numpy.lib
NAME
numpy.lib.scimath
DESCRIPTION
Wrapper functions to more user-friendly calling of certain math functions
whose output data-type is different than the input data-type in certain
domains of the input.
For example, for functions like `log` with branch cuts, the versions in this
module provide the mathematically valid answers in the complex plane::
>>> import math
>>> np.emath.log(-math.exp(1)) == (1+1j*math.pi)
True
Similarly, `sqrt`, other base logarithms, `power` and trig functions are
correctly handled. See their respective docstrings for specific examples.
Functions
---------
.. autosummary::
:toctree: generated/
sqrt
log
log2
logn
log10
power
arccos
arcsin
arctanh
FUNCTIONS
arccos(x)
Compute the inverse cosine of x.
Return the "principal value" (for a description of this, see
`numpy.arccos`) of the inverse cosine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[0, \pi]`. Otherwise, the complex principle value is returned.
Parameters
----------
x : array_like or scalar
The value(s) whose arccos is (are) required.
Returns
-------
out : ndarray or scalar
The inverse cosine(s) of the `x` value(s). If `x` was a scalar, so
is `out`, otherwise an array object is returned.
See Also
--------
numpy.arccos
Notes
-----
For an arccos() that returns ``NAN`` when real `x` is not in the
interval ``[-1,1]``, use `numpy.arccos`.
Examples
--------
>>> import numpy as np
>>> np.set_printoptions(precision=4)
>>> np.emath.arccos(1) # a scalar is returned
0.0
>>> np.emath.arccos([1,2])
array([0.-0.j , 0.-1.317j])
arcsin(x)
Compute the inverse sine of x.
Return the "principal value" (for a description of this, see
`numpy.arcsin`) of the inverse sine of `x`. For real `x` such that
`abs(x) <= 1`, this is a real number in the closed interval
:math:`[-\pi/2, \pi/2]`. Otherwise, the complex principle value is
returned.
Parameters
----------
x : array_like or scalar
The value(s) whose arcsin is (are) required.
Returns
-------
out : ndarray or scalar
The inverse sine(s) of the `x` value(s). If `x` was a scalar, so
is `out`, otherwise an array object is returned.
See Also
--------
numpy.arcsin
Notes
-----
For an arcsin() that returns ``NAN`` when real `x` is not in the
interval ``[-1,1]``, use `numpy.arcsin`.
Examples
--------
>>> import numpy as np
>>> np.set_printoptions(precision=4)
>>> np.emath.arcsin(0)
0.0
>>> np.emath.arcsin([0,1])
array([0. , 1.5708])
arctanh(x)
Compute the inverse hyperbolic tangent of `x`.
Return the "principal value" (for a description of this, see
`numpy.arctanh`) of ``arctanh(x)``. For real `x` such that
``abs(x) < 1``, this is a real number. If `abs(x) > 1`, or if `x` is
complex, the result is complex. Finally, `x = 1` returns``inf`` and
``x=-1`` returns ``-inf``.
Parameters
----------
x : array_like
The value(s) whose arctanh is (are) required.
Returns
-------
out : ndarray or scalar
The inverse hyperbolic tangent(s) of the `x` value(s). If `x` was
a scalar so is `out`, otherwise an array is returned.
See Also
--------
numpy.arctanh
Notes
-----
For an arctanh() that returns ``NAN`` when real `x` is not in the
interval ``(-1,1)``, use `numpy.arctanh` (this latter, however, does
return +/-inf for ``x = +/-1``).
Examples
--------
>>> import numpy as np
>>> np.set_printoptions(precision=4)
>>> np.emath.arctanh(0.5)
0.5493061443340549
>>> from numpy.testing import suppress_warnings
>>> with suppress_warnings() as sup:
... sup.filter(RuntimeWarning)
... np.emath.arctanh(np.eye(2))
array([[inf, 0.],
[ 0., inf]])
>>> np.emath.arctanh([1j])
array([0.+0.7854j])
log(x)
Compute the natural logarithm of `x`.
Return the "principal value" (for a description of this, see `numpy.log`)
of :math:`log_e(x)`. For real `x > 0`, this is a real number (``log(0)``
returns ``-inf`` and ``log(np.inf)`` returns ``inf``). Otherwise, the
complex principle value is returned.
Parameters
----------
x : array_like
The value(s) whose log is (are) required.
Returns
-------
out : ndarray or scalar
The log of the `x` value(s). If `x` was a scalar, so is `out`,
otherwise an array is returned.
See Also
--------
numpy.log
Notes
-----
For a log() that returns ``NAN`` when real `x < 0`, use `numpy.log`
(note, however, that otherwise `numpy.log` and this `log` are identical,
i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and,
notably, the complex principle value if ``x.imag != 0``).
Examples
--------
>>> import numpy as np
>>> np.emath.log(np.exp(1))
1.0
Negative arguments are handled "correctly" (recall that
``exp(log(x)) == x`` does *not* hold for real ``x < 0``):
>>> np.emath.log(-np.exp(1)) == (1 + np.pi * 1j)
True
log10(x)
Compute the logarithm base 10 of `x`.
Return the "principal value" (for a description of this, see
`numpy.log10`) of :math:`log_{10}(x)`. For real `x > 0`, this
is a real number (``log10(0)`` returns ``-inf`` and ``log10(np.inf)``
returns ``inf``). Otherwise, the complex principle value is returned.
Parameters
----------
x : array_like or scalar
The value(s) whose log base 10 is (are) required.
Returns
-------
out : ndarray or scalar
The log base 10 of the `x` value(s). If `x` was a scalar, so is `out`,
otherwise an array object is returned.
See Also
--------
numpy.log10
Notes
-----
For a log10() that returns ``NAN`` when real `x < 0`, use `numpy.log10`
(note, however, that otherwise `numpy.log10` and this `log10` are
identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`,
and, notably, the complex principle value if ``x.imag != 0``).
Examples
--------
>>> import numpy as np
(We set the printing precision so the example can be auto-tested)
>>> np.set_printoptions(precision=4)
>>> np.emath.log10(10**1)
1.0
>>> np.emath.log10([-10**1, -10**2, 10**2])
array([1.+1.3644j, 2.+1.3644j, 2.+0.j ])
log2(x)
Compute the logarithm base 2 of `x`.
Return the "principal value" (for a description of this, see
`numpy.log2`) of :math:`log_2(x)`. For real `x > 0`, this is
a real number (``log2(0)`` returns ``-inf`` and ``log2(np.inf)`` returns
``inf``). Otherwise, the complex principle value is returned.
Parameters
----------
x : array_like
The value(s) whose log base 2 is (are) required.
Returns
-------
out : ndarray or scalar
The log base 2 of the `x` value(s). If `x` was a scalar, so is `out`,
otherwise an array is returned.
See Also
--------
numpy.log2
Notes
-----
For a log2() that returns ``NAN`` when real `x < 0`, use `numpy.log2`
(note, however, that otherwise `numpy.log2` and this `log2` are
identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`,
and, notably, the complex principle value if ``x.imag != 0``).
Examples
--------
We set the printing precision so the example can be auto-tested:
>>> np.set_printoptions(precision=4)
>>> np.emath.log2(8)
3.0
>>> np.emath.log2([-4, -8, 8])
array([2.+4.5324j, 3.+4.5324j, 3.+0.j ])
logn(n, x)
Take log base n of x.
If `x` contains negative inputs, the answer is computed and returned in the
complex domain.
Parameters
----------
n : array_like
The integer base(s) in which the log is taken.
x : array_like
The value(s) whose log base `n` is (are) required.
Returns
-------
out : ndarray or scalar
The log base `n` of the `x` value(s). If `x` was a scalar, so is
`out`, otherwise an array is returned.
Examples
--------
>>> import numpy as np
>>> np.set_printoptions(precision=4)
>>> np.emath.logn(2, [4, 8])
array([2., 3.])
>>> np.emath.logn(2, [-4, -8, 8])
array([2.+4.5324j, 3.+4.5324j, 3.+0.j ])
power(x, p)
Return x to the power p, (x**p).
If `x` contains negative values, the output is converted to the
complex domain.
Parameters
----------
x : array_like
The input value(s).
p : array_like of ints
The power(s) to which `x` is raised. If `x` contains multiple values,
`p` has to either be a scalar, or contain the same number of values
as `x`. In the latter case, the result is
``x[0]**p[0], x[1]**p[1], ...``.
Returns
-------
out : ndarray or scalar
The result of ``x**p``. If `x` and `p` are scalars, so is `out`,
otherwise an array is returned.
See Also
--------
numpy.power
Examples
--------
>>> import numpy as np
>>> np.set_printoptions(precision=4)
>>> np.emath.power(2, 2)
4
>>> np.emath.power([2, 4], 2)
array([ 4, 16])
>>> np.emath.power([2, 4], -2)
array([0.25 , 0.0625])
>>> np.emath.power([-2, 4], 2)
array([ 4.-0.j, 16.+0.j])
>>> np.emath.power([2, 4], [2, 4])
array([ 4, 256])
sqrt(x)
Compute the square root of x.
For negative input elements, a complex value is returned
(unlike `numpy.sqrt` which returns NaN).
Parameters
----------
x : array_like
The input value(s).
Returns
-------
out : ndarray or scalar
The square root of `x`. If `x` was a scalar, so is `out`,
otherwise an array is returned.
See Also
--------
numpy.sqrt
Examples
--------
For real, non-negative inputs this works just like `numpy.sqrt`:
>>> import numpy as np
>>> np.emath.sqrt(1)
1.0
>>> np.emath.sqrt([1, 4])
array([1., 2.])
But it automatically handles negative inputs:
>>> np.emath.sqrt(-1)
1j
>>> np.emath.sqrt([-1,4])
array([0.+1.j, 2.+0.j])
Different results are expected because:
floating point 0.0 and -0.0 are distinct.
For more control, explicitly use complex() as follows:
>>> np.emath.sqrt(complex(-4.0, 0.0))
2j
>>> np.emath.sqrt(complex(-4.0, -0.0))
-2j
DATA
__all__ = ['sqrt', 'log', 'log2', 'logn', 'log10', 'power', 'arccos', ...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\lib\scimath.py
numpy.empty
Python Library Documentation: built-in function empty in module numpy
empty(...)
empty(shape, dtype=float, order='C', *, device=None, like=None)
Return a new array of given shape and type, without initializing entries.
Parameters
----------
shape : int or tuple of int
Shape of the empty array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
Desired output data-type for the array, e.g, `numpy.int8`. Default is
`numpy.float64`.
order : {'C', 'F'}, optional, default: 'C'
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
device : str, optional
The device on which to place the created array. Default: ``None``.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
Array of uninitialized (arbitrary) data of the given shape, dtype, and
order. Object arrays will be initialized to None.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones : Return a new array setting values to one.
zeros : Return a new array setting values to zero.
full : Return a new array of given shape filled with value.
Notes
-----
Unlike other array creation functions (e.g. `zeros`, `ones`, `full`),
`empty` does not initialize the values of the array, and may therefore be
marginally faster. However, the values stored in the newly allocated array
are arbitrary. For reproducible behavior, be sure to set each element of
the array before reading.
Examples
--------
>>> import numpy as np
>>> np.empty([2, 2])
array([[ -9.74499359e+001, 6.69583040e-309],
[ 2.13182611e-314, 3.06959433e-309]]) #uninitialized
>>> np.empty([2, 2], dtype=int)
array([[-1073741821, -1067949133],
[ 496041986, 19249760]]) #uninitialized
numpy.empty_like
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
empty_like(...)
empty_like(prototype, dtype=None, order='K', subok=True, shape=None, *,
device=None)
Return a new array with the same shape and type as a given array.
Parameters
----------
prototype : array_like
The shape and data-type of `prototype` define these same attributes
of the returned array.
dtype : data-type, optional
Overrides the data type of the result.
.. versionadded:: 1.6.0
order : {'C', 'F', 'A', or 'K'}, optional
Overrides the memory layout of the result. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `prototype` is Fortran
contiguous, 'C' otherwise. 'K' means match the layout of `prototype`
as closely as possible.
.. versionadded:: 1.6.0
subok : bool, optional.
If True, then the newly created array will use the sub-class
type of `prototype`, otherwise it will be a base-class array. Defaults
to True.
shape : int 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.
.. versionadded:: 1.17.0
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
Array of uninitialized (arbitrary) data with the same
shape and type as `prototype`.
See Also
--------
ones_like : Return an array of ones with shape and type of input.
zeros_like : Return an array of zeros with shape and type of input.
full_like : Return a new array with shape of input filled with value.
empty : Return a new uninitialized array.
Notes
-----
Unlike other array creation functions (e.g. `zeros_like`, `ones_like`,
`full_like`), `empty_like` does not initialize the values of the array,
and may therefore be marginally faster. However, the values stored in the
newly allocated array are arbitrary. For reproducible behavior, be sure
to set each element of the array before reading.
Examples
--------
>>> import numpy as np
>>> a = ([1,2,3], [4,5,6]) # a is array-like
>>> np.empty_like(a)
array([[-1073741821, -1073741821, 3], # uninitialized
[ 0, 0, -1073741821]])
>>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
>>> np.empty_like(a)
array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninitialized
[ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]])
numpy.equal
Python Library Documentation: ufunc
equal = <ufunc 'equal'>
equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return (x1 == x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Output array, element-wise comparison of `x1` and `x2`.
Typically of type bool, unless ``dtype=object`` is passed.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
not_equal, greater_equal, less_equal, greater, less
Examples
--------
>>> import numpy as np
>>> np.equal([0, 1, 3], np.arange(3))
array([ True, True, False])
What is compared are values, not types. So an int (1) and an array of
length one can evaluate as True:
>>> np.equal(1, np.ones(1))
array([ True])
The ``==`` operator can be used as a shorthand for ``np.equal`` on
ndarrays.
>>> a = np.array([2, 4, 6])
>>> b = np.array([2, 4, 2])
>>> a == b
array([ True, True, False])
numpy.errstate
Python Library Documentation: class errstate in module numpy
class errstate(builtins.object)
| errstate(*, call=<numpy._core._ufunc_config._unspecified object at 0x000002E7AA2F29F0>, all=None, divide=None, over=None, under=None, invalid=None)
|
| errstate(**kwargs)
|
| Context manager for floating-point error handling.
|
| Using an instance of `errstate` as a context manager allows statements in
| that context to execute with a known error handling behavior. Upon entering
| the context the error handling is set with `seterr` and `seterrcall`, and
| upon exiting it is reset to what it was before.
|
| .. versionchanged:: 1.17.0
| `errstate` is also usable as a function decorator, saving
| a level of indentation if an entire function is wrapped.
|
| .. versionchanged:: 2.0
| `errstate` is now fully thread and asyncio safe, but may not be
| entered more than once.
| It is not safe to decorate async functions using ``errstate``.
|
| Parameters
| ----------
| kwargs : {divide, over, under, invalid}
| Keyword arguments. The valid keywords are the possible floating-point
| exceptions. Each keyword should have a string value that defines the
| treatment for the particular error. Possible values are
| {'ignore', 'warn', 'raise', 'call', 'print', 'log'}.
|
| See Also
| --------
| seterr, geterr, seterrcall, geterrcall
|
| Notes
| -----
| For complete documentation of the types of floating-point exceptions and
| treatment options, see `seterr`.
|
| Examples
| --------
| >>> import numpy as np
| >>> olderr = np.seterr(all='ignore') # Set error handling to known state.
|
| >>> np.arange(3) / 0.
| array([nan, inf, inf])
| >>> with np.errstate(divide='ignore'):
| ... np.arange(3) / 0.
| array([nan, inf, inf])
|
| >>> np.sqrt(-1)
| np.float64(nan)
| >>> with np.errstate(invalid='raise'):
| ... np.sqrt(-1)
| Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| FloatingPointError: invalid value encountered in sqrt
|
| Outside the context the error handling behavior has not changed:
|
| >>> np.geterr()
| {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
| >>> olderr = np.seterr(**olderr) # restore original state
|
| Methods defined here:
|
| __call__(self, func) from numpy._core._ufunc_config.errstate
| Call self as a function.
|
| __enter__(self) from numpy._core._ufunc_config.errstate
|
| __exit__(self, *exc_info) from numpy._core._ufunc_config.errstate
|
| __init__(self, *, call=<numpy._core._ufunc_config._unspecified object at 0x000002E7AA2F29F0>, all=None, divide=None, over=None, under=None, invalid=None) from numpy._core._ufunc_config.errstate
| Initialize self. See help(type(self)) for accurate signature.
numpy.euler_gamma
Python Library Documentation: float object
class float(object)
| float(x=0, /)
|
| Convert a string or number to a floating-point number, if possible.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(self, /)
| Return the ceiling as an Integral.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(self, /)
| Return the floor as an Integral.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Formats the float according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __round__(self, ndigits=None, /)
| Return the Integral closest to x, rounding half toward even.
|
| When an argument is passed, work like built-in round(x, ndigits).
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| as_integer_ratio(self, /)
| Return a pair of integers, whose ratio is exactly equal to the original float.
|
| The ratio is in lowest terms and has a positive denominator. Raise
| OverflowError on infinities and a ValueError on NaNs.
|
| >>> (10.0).as_integer_ratio()
| (10, 1)
| >>> (0.0).as_integer_ratio()
| (0, 1)
| >>> (-.25).as_integer_ratio()
| (-1, 4)
|
| conjugate(self, /)
| Return self, the complex conjugate of any float.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> 3.14159.hex()
| '0x1.921f9f01b866ep+1'
|
| is_integer(self, /)
| Return True if the float is an integer.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __getformat__(typestr, /)
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
| little-endian' best describes the format of floating-point numbers used by the
| C type named by typestr.
|
| fromhex(string, /)
| Create a floating-point number from a hexadecimal string.
|
| >>> float.fromhex('0x1.ffffp10')
| 2047.984375
| >>> float.fromhex('-0x1p-1074')
| -5e-324
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| imag
| the imaginary part of a complex number
|
| real
| the real part of a complex number
numpy.exceptions
Python Library Documentation: module numpy.exceptions in numpy
NAME
numpy.exceptions
DESCRIPTION
Exceptions and Warnings (:mod:`numpy.exceptions`)
=================================================
General exceptions used by NumPy. Note that some exceptions may be module
specific, such as linear algebra errors.
.. versionadded:: NumPy 1.25
The exceptions module is new in NumPy 1.25. Older exceptions remain
available through the main NumPy namespace for compatibility.
.. currentmodule:: numpy.exceptions
Warnings
--------
.. autosummary::
:toctree: generated/
ComplexWarning Given when converting complex to real.
VisibleDeprecationWarning Same as a DeprecationWarning, but more visible.
RankWarning Issued when the design matrix is rank deficient.
Exceptions
----------
.. autosummary::
:toctree: generated/
AxisError Given when an axis was invalid.
DTypePromotionError Given when no common dtype could be found.
TooHardError Error specific to `numpy.shares_memory`.
CLASSES
builtins.DeprecationWarning(builtins.Warning)
ModuleDeprecationWarning
builtins.IndexError(builtins.LookupError)
AxisError(builtins.ValueError, builtins.IndexError)
builtins.RuntimeError(builtins.Exception)
TooHardError
builtins.RuntimeWarning(builtins.Warning)
ComplexWarning
builtins.TypeError(builtins.Exception)
DTypePromotionError
builtins.UserWarning(builtins.Warning)
VisibleDeprecationWarning
builtins.ValueError(builtins.Exception)
AxisError(builtins.ValueError, builtins.IndexError)
class AxisError(builtins.ValueError, builtins.IndexError)
| AxisError(axis, ndim=None, msg_prefix=None)
|
| Axis supplied was invalid.
|
| This is raised whenever an ``axis`` parameter is specified that is larger
| than the number of array dimensions.
| For compatibility with code written against older numpy versions, which
| raised a mixture of :exc:`ValueError` and :exc:`IndexError` for this
| situation, this exception subclasses both to ensure that
| ``except ValueError`` and ``except IndexError`` statements continue
| to catch ``AxisError``.
|
| .. versionadded:: 1.13
|
| Parameters
| ----------
| axis : int or str
| The out of bounds axis or a custom exception message.
| If an axis is provided, then `ndim` should be specified as well.
| ndim : int, optional
| The number of array dimensions.
| msg_prefix : str, optional
| A prefix for the exception message.
|
| Attributes
| ----------
| axis : int, optional
| The out of bounds axis or ``None`` if a custom exception
| message was provided. This should be the axis as passed by
| the user, before any normalization to resolve negative indices.
|
| .. versionadded:: 1.22
| ndim : int, optional
| The number of array dimensions or ``None`` if a custom exception
| message was provided.
|
| .. versionadded:: 1.22
|
|
| Examples
| --------
| >>> import numpy as np
| >>> array_1d = np.arange(10)
| >>> np.cumsum(array_1d, axis=1)
| Traceback (most recent call last):
| ...
| numpy.exceptions.AxisError: axis 1 is out of bounds for array of dimension 1
|
| Negative axes are preserved:
|
| >>> np.cumsum(array_1d, axis=-2)
| Traceback (most recent call last):
| ...
| numpy.exceptions.AxisError: axis -2 is out of bounds for array of dimension 1
|
| The class constructor generally takes the axis and arrays'
| dimensionality as arguments:
|
| >>> print(np.exceptions.AxisError(2, 1, msg_prefix='error'))
| error: axis 2 is out of bounds for array of dimension 1
|
| Alternatively, a custom exception message can be passed:
|
| >>> print(np.exceptions.AxisError('Custom error message'))
| Custom error message
|
| Method resolution order:
| AxisError
| builtins.ValueError
| builtins.IndexError
| builtins.LookupError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, axis, ndim=None, msg_prefix=None)
| Initialize self. See help(type(self)) for accurate signature.
|
| __str__(self)
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| axis
|
| ndim
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.ValueError:
|
| __new__(*args, **kwargs) class method of builtins.ValueError
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ComplexWarning(builtins.RuntimeWarning)
| The warning raised when casting a complex dtype to a real dtype.
|
| As implemented, casting a complex number to a real discards its imaginary
| part, but this behavior may not be what the user actually wants.
|
| Method resolution order:
| ComplexWarning
| builtins.RuntimeWarning
| builtins.Warning
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.RuntimeWarning:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.RuntimeWarning:
|
| __new__(*args, **kwargs) class method of builtins.RuntimeWarning
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class DTypePromotionError(builtins.TypeError)
| Multiple DTypes could not be converted to a common one.
|
| This exception derives from ``TypeError`` and is raised whenever dtypes
| cannot be converted to a single common one. This can be because they
| are of a different category/class or incompatible instances of the same
| one (see Examples).
|
| Notes
| -----
| Many functions will use promotion to find the correct result and
| implementation. For these functions the error will typically be chained
| with a more specific error indicating that no implementation was found
| for the input dtypes.
|
| Typically promotion should be considered "invalid" between the dtypes of
| two arrays when `arr1 == arr2` can safely return all ``False`` because the
| dtypes are fundamentally different.
|
| Examples
| --------
| Datetimes and complex numbers are incompatible classes and cannot be
| promoted:
|
| >>> import numpy as np
| >>> np.result_type(np.dtype("M8[s]"), np.complex128) # doctest: +IGNORE_EXCEPTION_DETAIL
| Traceback (most recent call last):
| ...
| DTypePromotionError: The DType <class 'numpy.dtype[datetime64]'> could not
| be promoted by <class 'numpy.dtype[complex128]'>. This means that no common
| DType exists for the given inputs. For example they cannot be stored in a
| single array unless the dtype is `object`. The full list of DTypes is:
| (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[complex128]'>)
|
| For example for structured dtypes, the structure can mismatch and the
| same ``DTypePromotionError`` is given when two structured dtypes with
| a mismatch in their number of fields is given:
|
| >>> dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)])
| >>> dtype2 = np.dtype([("field1", np.float64)])
| >>> np.promote_types(dtype1, dtype2) # doctest: +IGNORE_EXCEPTION_DETAIL
| Traceback (most recent call last):
| ...
| DTypePromotionError: field names `('field1', 'field2')` and `('field1',)`
| mismatch.
|
| Method resolution order:
| DTypePromotionError
| builtins.TypeError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.TypeError:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.TypeError:
|
| __new__(*args, **kwargs) class method of builtins.TypeError
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ModuleDeprecationWarning(builtins.DeprecationWarning)
| Module deprecation warning.
|
| .. warning::
|
| This warning should not be used, since nose testing is not relevant
| anymore.
|
| The nose tester turns ordinary Deprecation warnings into test failures.
| That makes it hard to deprecate whole modules, because they get
| imported by default. So this is a special Deprecation warning that the
| nose tester will let pass without making tests fail.
|
| Method resolution order:
| ModuleDeprecationWarning
| builtins.DeprecationWarning
| builtins.Warning
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.DeprecationWarning:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.DeprecationWarning:
|
| __new__(*args, **kwargs) class method of builtins.DeprecationWarning
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class TooHardError(builtins.RuntimeError)
| max_work was exceeded.
|
| This is raised whenever the maximum number of candidate solutions
| to consider specified by the ``max_work`` parameter is exceeded.
| Assigning a finite number to max_work may have caused the operation
| to fail.
|
| Method resolution order:
| TooHardError
| builtins.RuntimeError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.RuntimeError:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.RuntimeError:
|
| __new__(*args, **kwargs) class method of builtins.RuntimeError
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class VisibleDeprecationWarning(builtins.UserWarning)
| Visible deprecation warning.
|
| By default, python will not show deprecation warnings, so this class
| can be used when a very visible warning is helpful, for example because
| the usage is most likely a user bug.
|
| Method resolution order:
| VisibleDeprecationWarning
| builtins.UserWarning
| builtins.Warning
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.UserWarning:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.UserWarning:
|
| __new__(*args, **kwargs) class method of builtins.UserWarning
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
DATA
__all__ = ['ComplexWarning', 'VisibleDeprecationWarning', 'ModuleDepre...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\exceptions.py
numpy.exp
Python Library Documentation: ufunc
exp = <ufunc 'exp'>
exp(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Calculate the exponential of all elements in the input array.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Output array, element-wise exponential of `x`.
This is a scalar if `x` is a scalar.
See Also
--------
expm1 : Calculate ``exp(x) - 1`` for all elements in the array.
exp2 : Calculate ``2**x`` for all elements in the array.
Notes
-----
The irrational number ``e`` is also known as Euler's number. It is
approximately 2.718281, and is the base of the natural logarithm,
``ln`` (this means that, if :math:`x = \ln y = \log_e y`,
then :math:`e^x = y`. For real input, ``exp(x)`` is always positive.
For complex arguments, ``x = a + ib``, we can write
:math:`e^x = e^a e^{ib}`. The first term, :math:`e^a`, is already
known (it is the real argument, described above). The second term,
:math:`e^{ib}`, is :math:`\cos b + i \sin b`, a function with
magnitude 1 and a periodic phase.
References
----------
.. [1] Wikipedia, "Exponential function",
https://en.wikipedia.org/wiki/Exponential_function
.. [2] M. Abramovitz and I. A. Stegun, "Handbook of Mathematical Functions
with Formulas, Graphs, and Mathematical Tables," Dover, 1964, p. 69,
https://personal.math.ubc.ca/~cbm/aands/page_69.htm
Examples
--------
Plot the magnitude and phase of ``exp(x)`` in the complex plane:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-2*np.pi, 2*np.pi, 100)
>>> xx = x + 1j * x[:, np.newaxis] # a + ib over complex plane
>>> out = np.exp(xx)
>>> plt.subplot(121)
>>> plt.imshow(np.abs(out),
... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap='gray')
>>> plt.title('Magnitude of exp(x)')
>>> plt.subplot(122)
>>> plt.imshow(np.angle(out),
... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap='hsv')
>>> plt.title('Phase (angle) of exp(x)')
>>> plt.show()
numpy.exp2
Python Library Documentation: ufunc
exp2 = <ufunc 'exp2'>
exp2(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Calculate `2**p` for all `p` in the input array.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Element-wise 2 to the power `x`.
This is a scalar if `x` is a scalar.
See Also
--------
power
Notes
-----
.. versionadded:: 1.3.0
Examples
--------
>>> import numpy as np
>>> np.exp2([2, 3])
array([ 4., 8.])
numpy.expand_dims
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
expand_dims(a, axis)
Expand the shape of an array.
Insert a new axis that will appear at the `axis` position in the expanded
array shape.
Parameters
----------
a : array_like
Input array.
axis : int or tuple of ints
Position in the expanded axes where the new axis (or axes) is placed.
.. deprecated:: 1.13.0
Passing an axis where ``axis > a.ndim`` will be treated as
``axis == a.ndim``, and passing ``axis < -a.ndim - 1`` will
be treated as ``axis == 0``. This behavior is deprecated.
.. versionchanged:: 1.18.0
A tuple of axes is now supported. Out of range axes as
described above are now forbidden and raise an
`~exceptions.AxisError`.
Returns
-------
result : ndarray
View of `a` with the number of dimensions increased.
See Also
--------
squeeze : The inverse operation, removing singleton dimensions
reshape : Insert, remove, and combine dimensions, and resize existing ones
atleast_1d, atleast_2d, atleast_3d
Examples
--------
>>> import numpy as np
>>> x = np.array([1, 2])
>>> x.shape
(2,)
The following is equivalent to ``x[np.newaxis, :]`` or ``x[np.newaxis]``:
>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)
The following is equivalent to ``x[:, np.newaxis]``:
>>> y = np.expand_dims(x, axis=1)
>>> y
array([[1],
[2]])
>>> y.shape
(2, 1)
``axis`` may also be a tuple:
>>> y = np.expand_dims(x, axis=(0, 1))
>>> y
array([[[1, 2]]])
>>> y = np.expand_dims(x, axis=(2, 0))
>>> y
array([[[1],
[2]]])
Note that some examples may use ``None`` instead of ``np.newaxis``. These
are the same objects:
>>> np.newaxis is None
True
numpy.expm1
Python Library Documentation: ufunc
expm1 = <ufunc 'expm1'>
expm1(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Calculate ``exp(x) - 1`` for all elements in the array.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Element-wise exponential minus one: ``out = exp(x) - 1``.
This is a scalar if `x` is a scalar.
See Also
--------
log1p : ``log(1 + x)``, the inverse of expm1.
Notes
-----
This function provides greater precision than ``exp(x) - 1``
for small values of ``x``.
Examples
--------
The true value of ``exp(1e-10) - 1`` is ``1.00000000005e-10`` to
about 32 significant digits. This example shows the superiority of
expm1 in this case.
>>> import numpy as np
>>> np.expm1(1e-10)
1.00000000005e-10
>>> np.exp(1e-10) - 1
1.000000082740371e-10
numpy.extract
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
extract(condition, arr)
Return the elements of an array that satisfy some condition.
This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If
`condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``.
Note that `place` does the exact opposite of `extract`.
Parameters
----------
condition : array_like
An array whose nonzero or True entries indicate the elements of `arr`
to extract.
arr : array_like
Input array of the same size as `condition`.
Returns
-------
extract : ndarray
Rank 1 array of values from `arr` where `condition` is True.
See Also
--------
take, put, copyto, compress, place
Examples
--------
>>> import numpy as np
>>> arr = np.arange(12).reshape((3, 4))
>>> arr
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> condition = np.mod(arr, 3)==0
>>> condition
array([[ True, False, False, True],
[False, False, True, False],
[False, True, False, False]])
>>> np.extract(condition, arr)
array([0, 3, 6, 9])
If `condition` is boolean:
>>> arr[condition]
array([0, 3, 6, 9])
numpy.eye
Python Library Documentation: function eye in module numpy
eye(N, M=None, k=0, dtype=<class 'float'>, order='C', *, device=None, like=None)
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the output.
M : int, optional
Number of columns in the output. If None, defaults to `N`.
k : int, optional
Index of the diagonal: 0 (the default) refers to the main diagonal,
a positive value refers to an upper diagonal, and a negative value
to a lower diagonal.
dtype : data-type, optional
Data-type of the returned array.
order : {'C', 'F'}, optional
Whether the output should be stored in row-major (C-style) or
column-major (Fortran-style) order in memory.
.. versionadded:: 1.14.0
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
I : ndarray of shape (N,M)
An array where all elements are equal to zero, except for the `k`-th
diagonal, whose values are equal to one.
See Also
--------
identity : (almost) equivalent function
diag : diagonal 2-D array from a 1-D array specified by the user.
Examples
--------
>>> import numpy as np
>>> np.eye(2, dtype=int)
array([[1, 0],
[0, 1]])
>>> np.eye(3, k=1)
array([[0., 1., 0.],
[0., 0., 1.],
[0., 0., 0.]])
numpy.f2py
Python Library Documentation: package numpy.f2py in numpy
NAME
numpy.f2py - Fortran to Python Interface Generator.
DESCRIPTION
Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
Copyright 2011 -- present NumPy Developers.
Permission to use, modify, and distribute this software is given under the terms
of the NumPy License.
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
PACKAGE CONTENTS
__main__
__version__
_backends (package)
_isocbind
_src_pyf
auxfuncs
capi_maps
cb_rules
cfuncs
common_rules
crackfortran
diagnose
f2py2e
f90mod_rules
func2subr
rules
symbolic
tests (package)
use_rules
FUNCTIONS
__dir__()
__getattr__(attr)
get_include()
Return the directory that contains the ``fortranobject.c`` and ``.h`` files.
.. note::
This function is not needed when building an extension with
`numpy.distutils` directly from ``.f`` and/or ``.pyf`` files
in one go.
Python extension modules built with f2py-generated code need to use
``fortranobject.c`` as a source file, and include the ``fortranobject.h``
header. This function can be used to obtain the directory containing
both of these files.
Returns
-------
include_path : str
Absolute path to the directory containing ``fortranobject.c`` and
``fortranobject.h``.
Notes
-----
.. versionadded:: 1.21.1
Unless the build system you are using has specific support for f2py,
building a Python extension using a ``.pyf`` signature file is a two-step
process. For a module ``mymod``:
* Step 1: run ``python -m numpy.f2py mymod.pyf --quiet``. This
generates ``mymodmodule.c`` and (if needed)
``mymod-f2pywrappers.f`` files next to ``mymod.pyf``.
* Step 2: build your Python extension module. This requires the
following source files:
* ``mymodmodule.c``
* ``mymod-f2pywrappers.f`` (if it was generated in Step 1)
* ``fortranobject.c``
See Also
--------
numpy.get_include : function that returns the numpy include directory
run_main(comline_list)
Equivalent to running::
f2py <args>
where ``<args>=string.join(<list>,' ')``, but in Python. Unless
``-h`` is used, this function returns a dictionary containing
information on generated modules and their dependencies on source
files.
You cannot build extension modules with this function, that is,
using ``-c`` is not allowed. Use the ``compile`` command instead.
Examples
--------
The command ``f2py -m scalar scalar.f`` can be executed from Python as
follows.
.. literalinclude:: ../../source/f2py/code/results/run_main_session.dat
:language: python
DATA
__all__ = ['run_main', 'get_include']
VERSION
<module 'numpy.f2py.__version__' from 'C:\\Users\\Youse\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\numpy\\f2py\\__version__.py'>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\f2py\__init__.py
numpy.fabs
Python Library Documentation: ufunc
fabs = <ufunc 'fabs'>
fabs(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the absolute values element-wise.
This function returns the absolute values (positive magnitude) of the
data in `x`. Complex values are not handled, use `absolute` to find the
absolute values of complex data.
Parameters
----------
x : array_like
The array of numbers for which the absolute values are required. If
`x` is a scalar, the result `y` will also be a scalar.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The absolute values of `x`, the returned values are always floats.
This is a scalar if `x` is a scalar.
See Also
--------
absolute : Absolute values including `complex` types.
Examples
--------
>>> import numpy as np
>>> np.fabs(-1)
1.0
>>> np.fabs([-1.2, 1.2])
array([ 1.2, 1.2])
numpy.fft
Python Library Documentation: package numpy.fft in numpy
NAME
numpy.fft
DESCRIPTION
Discrete Fourier Transform (:mod:`numpy.fft`)
=============================================
.. currentmodule:: numpy.fft
The SciPy module `scipy.fft` is a more comprehensive superset
of ``numpy.fft``, which includes only a basic set of routines.
Standard FFTs
-------------
.. autosummary::
:toctree: generated/
fft Discrete Fourier transform.
ifft Inverse discrete Fourier transform.
fft2 Discrete Fourier transform in two dimensions.
ifft2 Inverse discrete Fourier transform in two dimensions.
fftn Discrete Fourier transform in N-dimensions.
ifftn Inverse discrete Fourier transform in N dimensions.
Real FFTs
---------
.. autosummary::
:toctree: generated/
rfft Real discrete Fourier transform.
irfft Inverse real discrete Fourier transform.
rfft2 Real discrete Fourier transform in two dimensions.
irfft2 Inverse real discrete Fourier transform in two dimensions.
rfftn Real discrete Fourier transform in N dimensions.
irfftn Inverse real discrete Fourier transform in N dimensions.
Hermitian FFTs
--------------
.. autosummary::
:toctree: generated/
hfft Hermitian discrete Fourier transform.
ihfft Inverse Hermitian discrete Fourier transform.
Helper routines
---------------
.. autosummary::
:toctree: generated/
fftfreq Discrete Fourier Transform sample frequencies.
rfftfreq DFT sample frequencies (for usage with rfft, irfft).
fftshift Shift zero-frequency component to center of spectrum.
ifftshift Inverse of fftshift.
Background information
----------------------
Fourier analysis is fundamentally a method for expressing a function as a
sum of periodic components, and for recovering the function from those
components. When both the function and its Fourier transform are
replaced with discretized counterparts, it is called the discrete Fourier
transform (DFT). The DFT has become a mainstay of numerical computing in
part because of a very fast algorithm for computing it, called the Fast
Fourier Transform (FFT), which was known to Gauss (1805) and was brought
to light in its current form by Cooley and Tukey [CT]_. Press et al. [NR]_
provide an accessible introduction to Fourier analysis and its
applications.
Because the discrete Fourier transform separates its input into
components that contribute at discrete frequencies, it has a great number
of applications in digital signal processing, e.g., for filtering, and in
this context the discretized input to the transform is customarily
referred to as a *signal*, which exists in the *time domain*. The output
is called a *spectrum* or *transform* and exists in the *frequency
domain*.
Implementation details
----------------------
There are many ways to define the DFT, varying in the sign of the
exponent, normalization, etc. In this implementation, the DFT is defined
as
.. math::
A_k = \sum_{m=0}^{n-1} a_m \exp\left\{-2\pi i{mk \over n}\right\}
\qquad k = 0,\ldots,n-1.
The DFT is in general defined for complex inputs and outputs, and a
single-frequency component at linear frequency :math:`f` is
represented by a complex exponential
:math:`a_m = \exp\{2\pi i\,f m\Delta t\}`, where :math:`\Delta t`
is the sampling interval.
The values in the result follow so-called "standard" order: If ``A =
fft(a, n)``, then ``A[0]`` contains the zero-frequency term (the sum of
the signal), which is always purely real for real inputs. Then ``A[1:n/2]``
contains the positive-frequency terms, and ``A[n/2+1:]`` contains the
negative-frequency terms, in order of decreasingly negative frequency.
For an even number of input points, ``A[n/2]`` represents both positive and
negative Nyquist frequency, and is also purely real for real input. For
an odd number of input points, ``A[(n-1)/2]`` contains the largest positive
frequency, while ``A[(n+1)/2]`` contains the largest negative frequency.
The routine ``np.fft.fftfreq(n)`` returns an array giving the frequencies
of corresponding elements in the output. The routine
``np.fft.fftshift(A)`` shifts transforms and their frequencies to put the
zero-frequency components in the middle, and ``np.fft.ifftshift(A)`` undoes
that shift.
When the input `a` is a time-domain signal and ``A = fft(a)``, ``np.abs(A)``
is its amplitude spectrum and ``np.abs(A)**2`` is its power spectrum.
The phase spectrum is obtained by ``np.angle(A)``.
The inverse DFT is defined as
.. math::
a_m = \frac{1}{n}\sum_{k=0}^{n-1}A_k\exp\left\{2\pi i{mk\over n}\right\}
\qquad m = 0,\ldots,n-1.
It differs from the forward transform by the sign of the exponential
argument and the default normalization by :math:`1/n`.
Type Promotion
--------------
`numpy.fft` promotes ``float32`` and ``complex64`` arrays to ``float64`` and
``complex128`` arrays respectively. For an FFT implementation that does not
promote input arrays, see `scipy.fftpack`.
Normalization
-------------
The argument ``norm`` indicates which direction of the pair of direct/inverse
transforms is scaled and with what normalization factor.
The default normalization (``"backward"``) has the direct (forward) transforms
unscaled and the inverse (backward) transforms scaled by :math:`1/n`. It is
possible to obtain unitary transforms by setting the keyword argument ``norm``
to ``"ortho"`` so that both direct and inverse transforms are scaled by
:math:`1/\sqrt{n}`. Finally, setting the keyword argument ``norm`` to
``"forward"`` has the direct transforms scaled by :math:`1/n` and the inverse
transforms unscaled (i.e. exactly opposite to the default ``"backward"``).
`None` is an alias of the default option ``"backward"`` for backward
compatibility.
Real and Hermitian transforms
-----------------------------
When the input is purely real, its transform is Hermitian, i.e., the
component at frequency :math:`f_k` is the complex conjugate of the
component at frequency :math:`-f_k`, which means that for real
inputs there is no information in the negative frequency components that
is not already available from the positive frequency components.
The family of `rfft` functions is
designed to operate on real inputs, and exploits this symmetry by
computing only the positive frequency components, up to and including the
Nyquist frequency. Thus, ``n`` input points produce ``n/2+1`` complex
output points. The inverses of this family assumes the same symmetry of
its input, and for an output of ``n`` points uses ``n/2+1`` input points.
Correspondingly, when the spectrum is purely real, the signal is
Hermitian. The `hfft` family of functions exploits this symmetry by
using ``n/2+1`` complex points in the input (time) domain for ``n`` real
points in the frequency domain.
In higher dimensions, FFTs are used, e.g., for image analysis and
filtering. The computational efficiency of the FFT means that it can
also be a faster way to compute large convolutions, using the property
that a convolution in the time domain is equivalent to a point-by-point
multiplication in the frequency domain.
Higher dimensions
-----------------
In two dimensions, the DFT is defined as
.. math::
A_{kl} = \sum_{m=0}^{M-1} \sum_{n=0}^{N-1}
a_{mn}\exp\left\{-2\pi i \left({mk\over M}+{nl\over N}\right)\right\}
\qquad k = 0, \ldots, M-1;\quad l = 0, \ldots, N-1,
which extends in the obvious way to higher dimensions, and the inverses
in higher dimensions also extend in the same way.
References
----------
.. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
machine calculation of complex Fourier series," *Math. Comput.*
19: 297-301.
.. [NR] Press, W., Teukolsky, S., Vetterline, W.T., and Flannery, B.P.,
2007, *Numerical Recipes: The Art of Scientific Computing*, ch.
12-13. Cambridge Univ. Press, Cambridge, UK.
Examples
--------
For examples, see the various functions.
PACKAGE CONTENTS
_helper
_pocketfft
_pocketfft_umath
helper
tests (package)
FUNCTIONS
fft(a, n=None, axis=-1, norm=None, out=None)
Compute the one-dimensional discrete Fourier Transform.
This function computes the one-dimensional *n*-point discrete Fourier
Transform (DFT) with the efficient Fast Fourier Transform (FFT)
algorithm [CT].
Parameters
----------
a : array_like
Input array, can be complex.
n : int, optional
Length of the transformed axis of the output.
If `n` is smaller than the length of the input, the input is cropped.
If it is larger, the input is padded with zeros. If `n` is not given,
the length of the input along the axis specified by `axis` is used.
axis : int, optional
Axis over which to compute the FFT. If not given, the last axis is
used.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : complex ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype.
.. versionadded:: 2.0.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
Raises
------
IndexError
If `axis` is not a valid axis of `a`.
See Also
--------
numpy.fft : for definition of the DFT and conventions used.
ifft : The inverse of `fft`.
fft2 : The two-dimensional FFT.
fftn : The *n*-dimensional FFT.
rfftn : The *n*-dimensional FFT of real input.
fftfreq : Frequency bins for given FFT parameters.
Notes
-----
FFT (Fast Fourier Transform) refers to a way the discrete Fourier
Transform (DFT) can be calculated efficiently, by using symmetries in the
calculated terms. The symmetry is highest when `n` is a power of 2, and
the transform is therefore most efficient for these sizes.
The DFT is defined, with the conventions used in this implementation, in
the documentation for the `numpy.fft` module.
References
----------
.. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
machine calculation of complex Fourier series," *Math. Comput.*
19: 297-301.
Examples
--------
>>> import numpy as np
>>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
array([-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j,
2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j,
-1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j,
1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j])
In this example, real input has an FFT which is Hermitian, i.e., symmetric
in the real part and anti-symmetric in the imaginary part, as described in
the `numpy.fft` documentation:
>>> import matplotlib.pyplot as plt
>>> t = np.arange(256)
>>> sp = np.fft.fft(np.sin(t))
>>> freq = np.fft.fftfreq(t.shape[-1])
>>> plt.plot(freq, sp.real, freq, sp.imag)
[<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>]
>>> plt.show()
fft2(a, s=None, axes=(-2, -1), norm=None, out=None)
Compute the 2-dimensional discrete Fourier Transform.
This function computes the *n*-dimensional discrete Fourier Transform
over any axes in an *M*-dimensional array by means of the
Fast Fourier Transform (FFT). By default, the transform is computed over
the last two axes of the input array, i.e., a 2-dimensional FFT.
Parameters
----------
a : array_like
Input array, can be complex
s : sequence of ints, optional
Shape (length of each transformed axis) of the output
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
This corresponds to ``n`` for ``fft(x, n)``.
Along each axis, if the given shape is smaller than that of the input,
the input is cropped. If it is larger, the input is padded with zeros.
.. versionchanged:: 2.0
If it is ``-1``, the whole input is used (no padding/trimming).
If `s` is not given, the shape of the input along the axes specified
by `axes` is used.
.. deprecated:: 2.0
If `s` is not ``None``, `axes` must not be ``None`` either.
.. deprecated:: 2.0
`s` must contain only ``int`` s, not ``None`` values. ``None``
values currently mean that the default value for ``n`` is used
in the corresponding 1-D transform, but this behaviour is
deprecated.
axes : sequence of ints, optional
Axes over which to compute the FFT. If not given, the last two
axes are used. A repeated index in `axes` means the transform over
that axis is performed multiple times. A one-element sequence means
that a one-dimensional FFT is performed. Default: ``(-2, -1)``.
.. deprecated:: 2.0
If `s` is specified, the corresponding `axes` to be transformed
must not be ``None``.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : complex ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype for all axes (and hence only the
last axis can have ``s`` not equal to the shape at that axis).
.. versionadded:: 2.0.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axes
indicated by `axes`, or the last two axes if `axes` is not given.
Raises
------
ValueError
If `s` and `axes` have different length, or `axes` not given and
``len(s) != 2``.
IndexError
If an element of `axes` is larger than than the number of axes of `a`.
See Also
--------
numpy.fft : Overall view of discrete Fourier transforms, with definitions
and conventions used.
ifft2 : The inverse two-dimensional FFT.
fft : The one-dimensional FFT.
fftn : The *n*-dimensional FFT.
fftshift : Shifts zero-frequency terms to the center of the array.
For two-dimensional input, swaps first and third quadrants, and second
and fourth quadrants.
Notes
-----
`fft2` is just `fftn` with a different default for `axes`.
The output, analogously to `fft`, contains the term for zero frequency in
the low-order corner of the transformed axes, the positive frequency terms
in the first half of these axes, the term for the Nyquist frequency in the
middle of the axes and the negative frequency terms in the second half of
the axes, in order of decreasingly negative frequency.
See `fftn` for details and a plotting example, and `numpy.fft` for
definitions and conventions used.
Examples
--------
>>> import numpy as np
>>> a = np.mgrid[:5, :5][0]
>>> np.fft.fft2(a)
array([[ 50. +0.j , 0. +0.j , 0. +0.j , # may vary
0. +0.j , 0. +0.j ],
[-12.5+17.20477401j, 0. +0.j , 0. +0.j ,
0. +0.j , 0. +0.j ],
[-12.5 +4.0614962j , 0. +0.j , 0. +0.j ,
0. +0.j , 0. +0.j ],
[-12.5 -4.0614962j , 0. +0.j , 0. +0.j ,
0. +0.j , 0. +0.j ],
[-12.5-17.20477401j, 0. +0.j , 0. +0.j ,
0. +0.j , 0. +0.j ]])
fftfreq(n, d=1.0, device=None)
Return the Discrete Fourier Transform sample frequencies.
The returned float array `f` contains the frequency bin centers in cycles
per unit of the sample spacing (with zero at the start). For instance, if
the sample spacing is in seconds, then the frequency unit is cycles/second.
Given a window length `n` and a sample spacing `d`::
f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even
f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd
Parameters
----------
n : int
Window length.
d : scalar, optional
Sample spacing (inverse of the sampling rate). Defaults to 1.
device : str, optional
The device on which to place the created array. Default: ``None``.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
f : ndarray
Array of length `n` containing the sample frequencies.
Examples
--------
>>> import numpy as np
>>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
>>> fourier = np.fft.fft(signal)
>>> n = signal.size
>>> timestep = 0.1
>>> freq = np.fft.fftfreq(n, d=timestep)
>>> freq
array([ 0. , 1.25, 2.5 , ..., -3.75, -2.5 , -1.25])
fftn(a, s=None, axes=None, norm=None, out=None)
Compute the N-dimensional discrete Fourier Transform.
This function computes the *N*-dimensional discrete Fourier Transform over
any number of axes in an *M*-dimensional array by means of the Fast Fourier
Transform (FFT).
Parameters
----------
a : array_like
Input array, can be complex.
s : sequence of ints, optional
Shape (length of each transformed axis) of the output
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
This corresponds to ``n`` for ``fft(x, n)``.
Along any axis, if the given shape is smaller than that of the input,
the input is cropped. If it is larger, the input is padded with zeros.
.. versionchanged:: 2.0
If it is ``-1``, the whole input is used (no padding/trimming).
If `s` is not given, the shape of the input along the axes specified
by `axes` is used.
.. deprecated:: 2.0
If `s` is not ``None``, `axes` must not be ``None`` either.
.. deprecated:: 2.0
`s` must contain only ``int`` s, not ``None`` values. ``None``
values currently mean that the default value for ``n`` is used
in the corresponding 1-D transform, but this behaviour is
deprecated.
axes : sequence of ints, optional
Axes over which to compute the FFT. If not given, the last ``len(s)``
axes are used, or all axes if `s` is also not specified.
Repeated indices in `axes` means that the transform over that axis is
performed multiple times.
.. deprecated:: 2.0
If `s` is specified, the corresponding `axes` to be transformed
must be explicitly specified too.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : complex ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype for all axes (and hence is
incompatible with passing in all but the trivial ``s``).
.. versionadded:: 2.0.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axes
indicated by `axes`, or by a combination of `s` and `a`,
as explained in the parameters section above.
Raises
------
ValueError
If `s` and `axes` have different length.
IndexError
If an element of `axes` is larger than than the number of axes of `a`.
See Also
--------
numpy.fft : Overall view of discrete Fourier transforms, with definitions
and conventions used.
ifftn : The inverse of `fftn`, the inverse *n*-dimensional FFT.
fft : The one-dimensional FFT, with definitions and conventions used.
rfftn : The *n*-dimensional FFT of real input.
fft2 : The two-dimensional FFT.
fftshift : Shifts zero-frequency terms to centre of array
Notes
-----
The output, analogously to `fft`, contains the term for zero frequency in
the low-order corner of all axes, the positive frequency terms in the
first half of all axes, the term for the Nyquist frequency in the middle
of all axes and the negative frequency terms in the second half of all
axes, in order of decreasingly negative frequency.
See `numpy.fft` for details, definitions and conventions used.
Examples
--------
>>> import numpy as np
>>> a = np.mgrid[:3, :3, :3][0]
>>> np.fft.fftn(a, axes=(1, 2))
array([[[ 0.+0.j, 0.+0.j, 0.+0.j], # may vary
[ 0.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j, 0.+0.j]],
[[ 9.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j, 0.+0.j]],
[[18.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j, 0.+0.j]]])
>>> np.fft.fftn(a, (2, 2), axes=(0, 1))
array([[[ 2.+0.j, 2.+0.j, 2.+0.j], # may vary
[ 0.+0.j, 0.+0.j, 0.+0.j]],
[[-2.+0.j, -2.+0.j, -2.+0.j],
[ 0.+0.j, 0.+0.j, 0.+0.j]]])
>>> import matplotlib.pyplot as plt
>>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
... 2 * np.pi * np.arange(200) / 34)
>>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape)
>>> FS = np.fft.fftn(S)
>>> plt.imshow(np.log(np.abs(np.fft.fftshift(FS))**2))
<matplotlib.image.AxesImage object at 0x...>
>>> plt.show()
fftshift(x, axes=None)
Shift the zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes listed (defaults to all).
Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
Parameters
----------
x : array_like
Input array.
axes : int or shape tuple, optional
Axes over which to shift. Default is None, which shifts all axes.
Returns
-------
y : ndarray
The shifted array.
See Also
--------
ifftshift : The inverse of `fftshift`.
Examples
--------
>>> import numpy as np
>>> freqs = np.fft.fftfreq(10, 0.1)
>>> freqs
array([ 0., 1., 2., ..., -3., -2., -1.])
>>> np.fft.fftshift(freqs)
array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.])
Shift the zero-frequency component only along the second axis:
>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0., 1., 2.],
[ 3., 4., -4.],
[-3., -2., -1.]])
>>> np.fft.fftshift(freqs, axes=(1,))
array([[ 2., 0., 1.],
[-4., 3., 4.],
[-1., -3., -2.]])
hfft(a, n=None, axis=-1, norm=None, out=None)
Compute the FFT of a signal that has Hermitian symmetry, i.e., a real
spectrum.
Parameters
----------
a : array_like
The input array.
n : int, optional
Length of the transformed axis of the output. For `n` output
points, ``n//2 + 1`` input points are necessary. If the input is
longer than this, it is cropped. If it is shorter than this, it is
padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``
where ``m`` is the length of the input along the axis specified by
`axis`.
axis : int, optional
Axis over which to compute the FFT. If not given, the last
axis is used.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype.
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
The length of the transformed axis is `n`, or, if `n` is not given,
``2*m - 2`` where ``m`` is the length of the transformed axis of
the input. To get an odd number of output points, `n` must be
specified, for instance as ``2*m - 1`` in the typical case,
Raises
------
IndexError
If `axis` is not a valid axis of `a`.
See also
--------
rfft : Compute the one-dimensional FFT for real input.
ihfft : The inverse of `hfft`.
Notes
-----
`hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
opposite case: here the signal has Hermitian symmetry in the time
domain and is real in the frequency domain. So here it's `hfft` for
which you must supply the length of the result if it is to be odd.
* even: ``ihfft(hfft(a, 2*len(a) - 2)) == a``, within roundoff error,
* odd: ``ihfft(hfft(a, 2*len(a) - 1)) == a``, within roundoff error.
The correct interpretation of the hermitian input depends on the length of
the original data, as given by `n`. This is because each input shape could
correspond to either an odd or even length signal. By default, `hfft`
assumes an even output length which puts the last entry at the Nyquist
frequency; aliasing with its symmetric counterpart. By Hermitian symmetry,
the value is thus treated as purely real. To avoid losing information, the
shape of the full signal **must** be given.
Examples
--------
>>> import numpy as np
>>> signal = np.array([1, 2, 3, 4, 3, 2])
>>> np.fft.fft(signal)
array([15.+0.j, -4.+0.j, 0.+0.j, -1.-0.j, 0.+0.j, -4.+0.j]) # may vary
>>> np.fft.hfft(signal[:4]) # Input first half of signal
array([15., -4., 0., -1., 0., -4.])
>>> np.fft.hfft(signal, 6) # Input entire signal and truncate
array([15., -4., 0., -1., 0., -4.])
>>> signal = np.array([[1, 1.j], [-1.j, 2]])
>>> np.conj(signal.T) - signal # check Hermitian symmetry
array([[ 0.-0.j, -0.+0.j], # may vary
[ 0.+0.j, 0.-0.j]])
>>> freq_spectrum = np.fft.hfft(signal)
>>> freq_spectrum
array([[ 1., 1.],
[ 2., -2.]])
ifft(a, n=None, axis=-1, norm=None, out=None)
Compute the one-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the one-dimensional *n*-point
discrete Fourier transform computed by `fft`. In other words,
``ifft(fft(a)) == a`` to within numerical accuracy.
For a general description of the algorithm and definitions,
see `numpy.fft`.
The input should be ordered in the same way as is returned by `fft`,
i.e.,
* ``a[0]`` should contain the zero frequency term,
* ``a[1:n//2]`` should contain the positive-frequency terms,
* ``a[n//2 + 1:]`` should contain the negative-frequency terms, in
increasing order starting from the most negative frequency.
For an even number of input points, ``A[n//2]`` represents the sum of
the values at the positive and negative Nyquist frequencies, as the two
are aliased together. See `numpy.fft` for details.
Parameters
----------
a : array_like
Input array, can be complex.
n : int, optional
Length of the transformed axis of the output.
If `n` is smaller than the length of the input, the input is cropped.
If it is larger, the input is padded with zeros. If `n` is not given,
the length of the input along the axis specified by `axis` is used.
See notes about padding issues.
axis : int, optional
Axis over which to compute the inverse DFT. If not given, the last
axis is used.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : complex ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype.
.. versionadded:: 2.0.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
Raises
------
IndexError
If `axis` is not a valid axis of `a`.
See Also
--------
numpy.fft : An introduction, with definitions and general explanations.
fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse
ifft2 : The two-dimensional inverse FFT.
ifftn : The n-dimensional inverse FFT.
Notes
-----
If the input parameter `n` is larger than the size of the input, the input
is padded by appending zeros at the end. Even though this is the common
approach, it might lead to surprising results. If a different padding is
desired, it must be performed before calling `ifft`.
Examples
--------
>>> import numpy as np
>>> np.fft.ifft([0, 4, 0, 0])
array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) # may vary
Create and plot a band-limited signal with random phases:
>>> import matplotlib.pyplot as plt
>>> t = np.arange(400)
>>> n = np.zeros((400,), dtype=complex)
>>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,)))
>>> s = np.fft.ifft(n)
>>> plt.plot(t, s.real, label='real')
[<matplotlib.lines.Line2D object at ...>]
>>> plt.plot(t, s.imag, '--', label='imaginary')
[<matplotlib.lines.Line2D object at ...>]
>>> plt.legend()
<matplotlib.legend.Legend object at ...>
>>> plt.show()
ifft2(a, s=None, axes=(-2, -1), norm=None, out=None)
Compute the 2-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the 2-dimensional discrete Fourier
Transform over any number of axes in an M-dimensional array by means of
the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(a)) == a``
to within numerical accuracy. By default, the inverse transform is
computed over the last two axes of the input array.
The input, analogously to `ifft`, should be ordered in the same way as is
returned by `fft2`, i.e. it should have the term for zero frequency
in the low-order corner of the two axes, the positive frequency terms in
the first half of these axes, the term for the Nyquist frequency in the
middle of the axes and the negative frequency terms in the second half of
both axes, in order of decreasingly negative frequency.
Parameters
----------
a : array_like
Input array, can be complex.
s : sequence of ints, optional
Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.
Along each axis, if the given shape is smaller than that of the input,
the input is cropped. If it is larger, the input is padded with zeros.
.. versionchanged:: 2.0
If it is ``-1``, the whole input is used (no padding/trimming).
If `s` is not given, the shape of the input along the axes specified
by `axes` is used. See notes for issue on `ifft` zero padding.
.. deprecated:: 2.0
If `s` is not ``None``, `axes` must not be ``None`` either.
.. deprecated:: 2.0
`s` must contain only ``int`` s, not ``None`` values. ``None``
values currently mean that the default value for ``n`` is used
in the corresponding 1-D transform, but this behaviour is
deprecated.
axes : sequence of ints, optional
Axes over which to compute the FFT. If not given, the last two
axes are used. A repeated index in `axes` means the transform over
that axis is performed multiple times. A one-element sequence means
that a one-dimensional FFT is performed. Default: ``(-2, -1)``.
.. deprecated:: 2.0
If `s` is specified, the corresponding `axes` to be transformed
must not be ``None``.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : complex ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype for all axes (and hence is
incompatible with passing in all but the trivial ``s``).
.. versionadded:: 2.0.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axes
indicated by `axes`, or the last two axes if `axes` is not given.
Raises
------
ValueError
If `s` and `axes` have different length, or `axes` not given and
``len(s) != 2``.
IndexError
If an element of `axes` is larger than than the number of axes of `a`.
See Also
--------
numpy.fft : Overall view of discrete Fourier transforms, with definitions
and conventions used.
fft2 : The forward 2-dimensional FFT, of which `ifft2` is the inverse.
ifftn : The inverse of the *n*-dimensional FFT.
fft : The one-dimensional FFT.
ifft : The one-dimensional inverse FFT.
Notes
-----
`ifft2` is just `ifftn` with a different default for `axes`.
See `ifftn` for details and a plotting example, and `numpy.fft` for
definition and conventions used.
Zero-padding, analogously with `ifft`, is performed by appending zeros to
the input along the specified dimension. Although this is the common
approach, it might lead to surprising results. If another form of zero
padding is desired, it must be performed before `ifft2` is called.
Examples
--------
>>> import numpy as np
>>> a = 4 * np.eye(4)
>>> np.fft.ifft2(a)
array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary
[0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j],
[0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
[0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]])
ifftn(a, s=None, axes=None, norm=None, out=None)
Compute the N-dimensional inverse discrete Fourier Transform.
This function computes the inverse of the N-dimensional discrete
Fourier Transform over any number of axes in an M-dimensional array by
means of the Fast Fourier Transform (FFT). In other words,
``ifftn(fftn(a)) == a`` to within numerical accuracy.
For a description of the definitions and conventions used, see `numpy.fft`.
The input, analogously to `ifft`, should be ordered in the same way as is
returned by `fftn`, i.e. it should have the term for zero frequency
in all axes in the low-order corner, the positive frequency terms in the
first half of all axes, the term for the Nyquist frequency in the middle
of all axes and the negative frequency terms in the second half of all
axes, in order of decreasingly negative frequency.
Parameters
----------
a : array_like
Input array, can be complex.
s : sequence of ints, optional
Shape (length of each transformed axis) of the output
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
This corresponds to ``n`` for ``ifft(x, n)``.
Along any axis, if the given shape is smaller than that of the input,
the input is cropped. If it is larger, the input is padded with zeros.
.. versionchanged:: 2.0
If it is ``-1``, the whole input is used (no padding/trimming).
If `s` is not given, the shape of the input along the axes specified
by `axes` is used. See notes for issue on `ifft` zero padding.
.. deprecated:: 2.0
If `s` is not ``None``, `axes` must not be ``None`` either.
.. deprecated:: 2.0
`s` must contain only ``int`` s, not ``None`` values. ``None``
values currently mean that the default value for ``n`` is used
in the corresponding 1-D transform, but this behaviour is
deprecated.
axes : sequence of ints, optional
Axes over which to compute the IFFT. If not given, the last ``len(s)``
axes are used, or all axes if `s` is also not specified.
Repeated indices in `axes` means that the inverse transform over that
axis is performed multiple times.
.. deprecated:: 2.0
If `s` is specified, the corresponding `axes` to be transformed
must be explicitly specified too.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : complex ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype for all axes (and hence is
incompatible with passing in all but the trivial ``s``).
.. versionadded:: 2.0.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axes
indicated by `axes`, or by a combination of `s` or `a`,
as explained in the parameters section above.
Raises
------
ValueError
If `s` and `axes` have different length.
IndexError
If an element of `axes` is larger than than the number of axes of `a`.
See Also
--------
numpy.fft : Overall view of discrete Fourier transforms, with definitions
and conventions used.
fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse.
ifft : The one-dimensional inverse FFT.
ifft2 : The two-dimensional inverse FFT.
ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
of array.
Notes
-----
See `numpy.fft` for definitions and conventions used.
Zero-padding, analogously with `ifft`, is performed by appending zeros to
the input along the specified dimension. Although this is the common
approach, it might lead to surprising results. If another form of zero
padding is desired, it must be performed before `ifftn` is called.
Examples
--------
>>> import numpy as np
>>> a = np.eye(4)
>>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,))
array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary
[0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],
[0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
[0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]])
Create and plot an image with band-limited frequency content:
>>> import matplotlib.pyplot as plt
>>> n = np.zeros((200,200), dtype=complex)
>>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20)))
>>> im = np.fft.ifftn(n).real
>>> plt.imshow(im)
<matplotlib.image.AxesImage object at 0x...>
>>> plt.show()
ifftshift(x, axes=None)
The inverse of `fftshift`. Although identical for even-length `x`, the
functions differ by one sample for odd-length `x`.
Parameters
----------
x : array_like
Input array.
axes : int or shape tuple, optional
Axes over which to calculate. Defaults to None, which shifts all axes.
Returns
-------
y : ndarray
The shifted array.
See Also
--------
fftshift : Shift zero-frequency component to the center of the spectrum.
Examples
--------
>>> import numpy as np
>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
>>> freqs
array([[ 0., 1., 2.],
[ 3., 4., -4.],
[-3., -2., -1.]])
>>> np.fft.ifftshift(np.fft.fftshift(freqs))
array([[ 0., 1., 2.],
[ 3., 4., -4.],
[-3., -2., -1.]])
ihfft(a, n=None, axis=-1, norm=None, out=None)
Compute the inverse FFT of a signal that has Hermitian symmetry.
Parameters
----------
a : array_like
Input array.
n : int, optional
Length of the inverse FFT, the number of points along
transformation axis in the input to use. If `n` is smaller than
the length of the input, the input is cropped. If it is larger,
the input is padded with zeros. If `n` is not given, the length of
the input along the axis specified by `axis` is used.
axis : int, optional
Axis over which to compute the inverse FFT. If not given, the last
axis is used.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : complex ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype.
.. versionadded:: 2.0.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
The length of the transformed axis is ``n//2 + 1``.
See also
--------
hfft, irfft
Notes
-----
`hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
opposite case: here the signal has Hermitian symmetry in the time
domain and is real in the frequency domain. So here it's `hfft` for
which you must supply the length of the result if it is to be odd:
* even: ``ihfft(hfft(a, 2*len(a) - 2)) == a``, within roundoff error,
* odd: ``ihfft(hfft(a, 2*len(a) - 1)) == a``, within roundoff error.
Examples
--------
>>> import numpy as np
>>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
>>> np.fft.ifft(spectrum)
array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.+0.j]) # may vary
>>> np.fft.ihfft(spectrum)
array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) # may vary
irfft(a, n=None, axis=-1, norm=None, out=None)
Computes the inverse of `rfft`.
This function computes the inverse of the one-dimensional *n*-point
discrete Fourier Transform of real input computed by `rfft`.
In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical
accuracy. (See Notes below for why ``len(a)`` is necessary here.)
The input is expected to be in the form returned by `rfft`, i.e. the
real zero-frequency term followed by the complex positive frequency terms
in order of increasing frequency. Since the discrete Fourier Transform of
real input is Hermitian-symmetric, the negative frequency terms are taken
to be the complex conjugates of the corresponding positive frequency terms.
Parameters
----------
a : array_like
The input array.
n : int, optional
Length of the transformed axis of the output.
For `n` output points, ``n//2+1`` input points are necessary. If the
input is longer than this, it is cropped. If it is shorter than this,
it is padded with zeros. If `n` is not given, it is taken to be
``2*(m-1)`` where ``m`` is the length of the input along the axis
specified by `axis`.
axis : int, optional
Axis over which to compute the inverse FFT. If not given, the last
axis is used.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype.
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
The length of the transformed axis is `n`, or, if `n` is not given,
``2*(m-1)`` where ``m`` is the length of the transformed axis of the
input. To get an odd number of output points, `n` must be specified.
Raises
------
IndexError
If `axis` is not a valid axis of `a`.
See Also
--------
numpy.fft : For definition of the DFT and conventions used.
rfft : The one-dimensional FFT of real input, of which `irfft` is inverse.
fft : The one-dimensional FFT.
irfft2 : The inverse of the two-dimensional FFT of real input.
irfftn : The inverse of the *n*-dimensional FFT of real input.
Notes
-----
Returns the real valued `n`-point inverse discrete Fourier transform
of `a`, where `a` contains the non-negative frequency terms of a
Hermitian-symmetric sequence. `n` is the length of the result, not the
input.
If you specify an `n` such that `a` must be zero-padded or truncated, the
extra/removed values will be added/removed at high frequencies. One can
thus resample a series to `m` points via Fourier interpolation by:
``a_resamp = irfft(rfft(a), m)``.
The correct interpretation of the hermitian input depends on the length of
the original data, as given by `n`. This is because each input shape could
correspond to either an odd or even length signal. By default, `irfft`
assumes an even output length which puts the last entry at the Nyquist
frequency; aliasing with its symmetric counterpart. By Hermitian symmetry,
the value is thus treated as purely real. To avoid losing information, the
correct length of the real input **must** be given.
Examples
--------
>>> import numpy as np
>>> np.fft.ifft([1, -1j, -1, 1j])
array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) # may vary
>>> np.fft.irfft([1, -1j, -1])
array([0., 1., 0., 0.])
Notice how the last term in the input to the ordinary `ifft` is the
complex conjugate of the second term, and the output has zero imaginary
part everywhere. When calling `irfft`, the negative frequencies are not
specified, and the output array is purely real.
irfft2(a, s=None, axes=(-2, -1), norm=None, out=None)
Computes the inverse of `rfft2`.
Parameters
----------
a : array_like
The input array
s : sequence of ints, optional
Shape of the real output to the inverse FFT.
.. versionchanged:: 2.0
If it is ``-1``, the whole input is used (no padding/trimming).
.. deprecated:: 2.0
If `s` is not ``None``, `axes` must not be ``None`` either.
.. deprecated:: 2.0
`s` must contain only ``int`` s, not ``None`` values. ``None``
values currently mean that the default value for ``n`` is used
in the corresponding 1-D transform, but this behaviour is
deprecated.
axes : sequence of ints, optional
The axes over which to compute the inverse fft.
Default: ``(-2, -1)``, the last two axes.
.. deprecated:: 2.0
If `s` is specified, the corresponding `axes` to be transformed
must not be ``None``.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype for the last transformation.
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
The result of the inverse real 2-D FFT.
See Also
--------
rfft2 : The forward two-dimensional FFT of real input,
of which `irfft2` is the inverse.
rfft : The one-dimensional FFT for real input.
irfft : The inverse of the one-dimensional FFT of real input.
irfftn : Compute the inverse of the N-dimensional FFT of real input.
Notes
-----
This is really `irfftn` with different defaults.
For more details see `irfftn`.
Examples
--------
>>> import numpy as np
>>> a = np.mgrid[:5, :5][0]
>>> A = np.fft.rfft2(a)
>>> np.fft.irfft2(A, s=a.shape)
array([[0., 0., 0., 0., 0.],
[1., 1., 1., 1., 1.],
[2., 2., 2., 2., 2.],
[3., 3., 3., 3., 3.],
[4., 4., 4., 4., 4.]])
irfftn(a, s=None, axes=None, norm=None, out=None)
Computes the inverse of `rfftn`.
This function computes the inverse of the N-dimensional discrete
Fourier Transform for real input over any number of axes in an
M-dimensional array by means of the Fast Fourier Transform (FFT). In
other words, ``irfftn(rfftn(a), a.shape) == a`` to within numerical
accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
and for the same reason.)
The input should be ordered in the same way as is returned by `rfftn`,
i.e. as for `irfft` for the final transformation axis, and as for `ifftn`
along all the other axes.
Parameters
----------
a : array_like
Input array.
s : sequence of ints, optional
Shape (length of each transformed axis) of the output
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
number of input points used along this axis, except for the last axis,
where ``s[-1]//2+1`` points of the input are used.
Along any axis, if the shape indicated by `s` is smaller than that of
the input, the input is cropped. If it is larger, the input is padded
with zeros.
.. versionchanged:: 2.0
If it is ``-1``, the whole input is used (no padding/trimming).
If `s` is not given, the shape of the input along the axes
specified by axes is used. Except for the last axis which is taken to
be ``2*(m-1)`` where ``m`` is the length of the input along that axis.
.. deprecated:: 2.0
If `s` is not ``None``, `axes` must not be ``None`` either.
.. deprecated:: 2.0
`s` must contain only ``int`` s, not ``None`` values. ``None``
values currently mean that the default value for ``n`` is used
in the corresponding 1-D transform, but this behaviour is
deprecated.
axes : sequence of ints, optional
Axes over which to compute the inverse FFT. If not given, the last
`len(s)` axes are used, or all axes if `s` is also not specified.
Repeated indices in `axes` means that the inverse transform over that
axis is performed multiple times.
.. deprecated:: 2.0
If `s` is specified, the corresponding `axes` to be transformed
must be explicitly specified too.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype for the last transformation.
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
The truncated or zero-padded input, transformed along the axes
indicated by `axes`, or by a combination of `s` or `a`,
as explained in the parameters section above.
The length of each transformed axis is as given by the corresponding
element of `s`, or the length of the input in every axis except for the
last one if `s` is not given. In the final transformed axis the length
of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
length of the final transformed axis of the input. To get an odd
number of output points in the final axis, `s` must be specified.
Raises
------
ValueError
If `s` and `axes` have different length.
IndexError
If an element of `axes` is larger than than the number of axes of `a`.
See Also
--------
rfftn : The forward n-dimensional FFT of real input,
of which `ifftn` is the inverse.
fft : The one-dimensional FFT, with definitions and conventions used.
irfft : The inverse of the one-dimensional FFT of real input.
irfft2 : The inverse of the two-dimensional FFT of real input.
Notes
-----
See `fft` for definitions and conventions used.
See `rfft` for definitions and conventions used for real input.
The correct interpretation of the hermitian input depends on the shape of
the original data, as given by `s`. This is because each input shape could
correspond to either an odd or even length signal. By default, `irfftn`
assumes an even output length which puts the last entry at the Nyquist
frequency; aliasing with its symmetric counterpart. When performing the
final complex to real transform, the last value is thus treated as purely
real. To avoid losing information, the correct shape of the real input
**must** be given.
Examples
--------
>>> import numpy as np
>>> a = np.zeros((3, 2, 2))
>>> a[0, 0, 0] = 3 * 2 * 2
>>> np.fft.irfftn(a)
array([[[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.]],
[[1., 1.],
[1., 1.]]])
rfft(a, n=None, axis=-1, norm=None, out=None)
Compute the one-dimensional discrete Fourier Transform for real input.
This function computes the one-dimensional *n*-point discrete Fourier
Transform (DFT) of a real-valued array by means of an efficient algorithm
called the Fast Fourier Transform (FFT).
Parameters
----------
a : array_like
Input array
n : int, optional
Number of points along transformation axis in the input to use.
If `n` is smaller than the length of the input, the input is cropped.
If it is larger, the input is padded with zeros. If `n` is not given,
the length of the input along the axis specified by `axis` is used.
axis : int, optional
Axis over which to compute the FFT. If not given, the last axis is
used.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : complex ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype.
.. versionadded:: 2.0.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axis
indicated by `axis`, or the last one if `axis` is not specified.
If `n` is even, the length of the transformed axis is ``(n/2)+1``.
If `n` is odd, the length is ``(n+1)/2``.
Raises
------
IndexError
If `axis` is not a valid axis of `a`.
See Also
--------
numpy.fft : For definition of the DFT and conventions used.
irfft : The inverse of `rfft`.
fft : The one-dimensional FFT of general (complex) input.
fftn : The *n*-dimensional FFT.
rfftn : The *n*-dimensional FFT of real input.
Notes
-----
When the DFT is computed for purely real input, the output is
Hermitian-symmetric, i.e. the negative frequency terms are just the complex
conjugates of the corresponding positive-frequency terms, and the
negative-frequency terms are therefore redundant. This function does not
compute the negative frequency terms, and the length of the transformed
axis of the output is therefore ``n//2 + 1``.
When ``A = rfft(a)`` and fs is the sampling frequency, ``A[0]`` contains
the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
If `n` is even, ``A[-1]`` contains the term representing both positive
and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
the largest positive frequency (fs/2*(n-1)/n), and is complex in the
general case.
If the input `a` contains an imaginary part, it is silently discarded.
Examples
--------
>>> import numpy as np
>>> np.fft.fft([0, 1, 0, 0])
array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) # may vary
>>> np.fft.rfft([0, 1, 0, 0])
array([ 1.+0.j, 0.-1.j, -1.+0.j]) # may vary
Notice how the final element of the `fft` output is the complex conjugate
of the second element, for real input. For `rfft`, this symmetry is
exploited to compute only the non-negative frequency terms.
rfft2(a, s=None, axes=(-2, -1), norm=None, out=None)
Compute the 2-dimensional FFT of a real array.
Parameters
----------
a : array
Input array, taken to be real.
s : sequence of ints, optional
Shape of the FFT.
.. versionchanged:: 2.0
If it is ``-1``, the whole input is used (no padding/trimming).
.. deprecated:: 2.0
If `s` is not ``None``, `axes` must not be ``None`` either.
.. deprecated:: 2.0
`s` must contain only ``int`` s, not ``None`` values. ``None``
values currently mean that the default value for ``n`` is used
in the corresponding 1-D transform, but this behaviour is
deprecated.
axes : sequence of ints, optional
Axes over which to compute the FFT. Default: ``(-2, -1)``.
.. deprecated:: 2.0
If `s` is specified, the corresponding `axes` to be transformed
must not be ``None``.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : complex ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype for the last inverse transform.
incompatible with passing in all but the trivial ``s``).
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
The result of the real 2-D FFT.
See Also
--------
rfftn : Compute the N-dimensional discrete Fourier Transform for real
input.
Notes
-----
This is really just `rfftn` with different default behavior.
For more details see `rfftn`.
Examples
--------
>>> import numpy as np
>>> a = np.mgrid[:5, :5][0]
>>> np.fft.rfft2(a)
array([[ 50. +0.j , 0. +0.j , 0. +0.j ],
[-12.5+17.20477401j, 0. +0.j , 0. +0.j ],
[-12.5 +4.0614962j , 0. +0.j , 0. +0.j ],
[-12.5 -4.0614962j , 0. +0.j , 0. +0.j ],
[-12.5-17.20477401j, 0. +0.j , 0. +0.j ]])
rfftfreq(n, d=1.0, device=None)
Return the Discrete Fourier Transform sample frequencies
(for usage with rfft, irfft).
The returned float array `f` contains the frequency bin centers in cycles
per unit of the sample spacing (with zero at the start). For instance, if
the sample spacing is in seconds, then the frequency unit is cycles/second.
Given a window length `n` and a sample spacing `d`::
f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even
f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd
Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
the Nyquist frequency component is considered to be positive.
Parameters
----------
n : int
Window length.
d : scalar, optional
Sample spacing (inverse of the sampling rate). Defaults to 1.
device : str, optional
The device on which to place the created array. Default: ``None``.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
f : ndarray
Array of length ``n//2 + 1`` containing the sample frequencies.
Examples
--------
>>> import numpy as np
>>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
>>> fourier = np.fft.rfft(signal)
>>> n = signal.size
>>> sample_rate = 100
>>> freq = np.fft.fftfreq(n, d=1./sample_rate)
>>> freq
array([ 0., 10., 20., ..., -30., -20., -10.])
>>> freq = np.fft.rfftfreq(n, d=1./sample_rate)
>>> freq
array([ 0., 10., 20., 30., 40., 50.])
rfftn(a, s=None, axes=None, norm=None, out=None)
Compute the N-dimensional discrete Fourier Transform for real input.
This function computes the N-dimensional discrete Fourier Transform over
any number of axes in an M-dimensional real array by means of the Fast
Fourier Transform (FFT). By default, all axes are transformed, with the
real transform performed over the last axis, while the remaining
transforms are complex.
Parameters
----------
a : array_like
Input array, taken to be real.
s : sequence of ints, optional
Shape (length along each transformed axis) to use from the input.
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
Along any axis, if the given shape is smaller than that of the input,
the input is cropped. If it is larger, the input is padded with zeros.
.. versionchanged:: 2.0
If it is ``-1``, the whole input is used (no padding/trimming).
If `s` is not given, the shape of the input along the axes specified
by `axes` is used.
.. deprecated:: 2.0
If `s` is not ``None``, `axes` must not be ``None`` either.
.. deprecated:: 2.0
`s` must contain only ``int`` s, not ``None`` values. ``None``
values currently mean that the default value for ``n`` is used
in the corresponding 1-D transform, but this behaviour is
deprecated.
axes : sequence of ints, optional
Axes over which to compute the FFT. If not given, the last ``len(s)``
axes are used, or all axes if `s` is also not specified.
.. deprecated:: 2.0
If `s` is specified, the corresponding `axes` to be transformed
must be explicitly specified too.
norm : {"backward", "ortho", "forward"}, optional
.. versionadded:: 1.10.0
Normalization mode (see `numpy.fft`). Default is "backward".
Indicates which direction of the forward/backward pair of transforms
is scaled and with what normalization factor.
.. versionadded:: 1.20.0
The "backward", "forward" values were added.
out : complex ndarray, optional
If provided, the result will be placed in this array. It should be
of the appropriate shape and dtype for all axes (and hence is
incompatible with passing in all but the trivial ``s``).
.. versionadded:: 2.0.0
Returns
-------
out : complex ndarray
The truncated or zero-padded input, transformed along the axes
indicated by `axes`, or by a combination of `s` and `a`,
as explained in the parameters section above.
The length of the last axis transformed will be ``s[-1]//2+1``,
while the remaining transformed axes will have lengths according to
`s`, or unchanged from the input.
Raises
------
ValueError
If `s` and `axes` have different length.
IndexError
If an element of `axes` is larger than than the number of axes of `a`.
See Also
--------
irfftn : The inverse of `rfftn`, i.e. the inverse of the n-dimensional FFT
of real input.
fft : The one-dimensional FFT, with definitions and conventions used.
rfft : The one-dimensional FFT of real input.
fftn : The n-dimensional FFT.
rfft2 : The two-dimensional FFT of real input.
Notes
-----
The transform for real input is performed over the last transformation
axis, as by `rfft`, then the transform over the remaining axes is
performed as by `fftn`. The order of the output is as for `rfft` for the
final transformation axis, and as for `fftn` for the remaining
transformation axes.
See `fft` for details, definitions and conventions used.
Examples
--------
>>> import numpy as np
>>> a = np.ones((2, 2, 2))
>>> np.fft.rfftn(a)
array([[[8.+0.j, 0.+0.j], # may vary
[0.+0.j, 0.+0.j]],
[[0.+0.j, 0.+0.j],
[0.+0.j, 0.+0.j]]])
>>> np.fft.rfftn(a, axes=(2, 0))
array([[[4.+0.j, 0.+0.j], # may vary
[4.+0.j, 0.+0.j]],
[[0.+0.j, 0.+0.j],
[0.+0.j, 0.+0.j]]])
DATA
__all__ = ['fft', 'ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn', '...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\fft\__init__.py
numpy.fill_diagonal
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
fill_diagonal(a, val, wrap=False)
Fill the main diagonal of the given array of any dimensionality.
For an array `a` with ``a.ndim >= 2``, the diagonal is the list of
values ``a[i, ..., i]`` with indices ``i`` all identical. This function
modifies the input array in-place without returning a value.
Parameters
----------
a : array, at least 2-D.
Array whose diagonal is to be filled in-place.
val : scalar or array_like
Value(s) to write on the diagonal. If `val` is scalar, the value is
written along the diagonal. If array-like, the flattened `val` is
written along the diagonal, repeating if necessary to fill all
diagonal entries.
wrap : bool
For tall matrices in NumPy version up to 1.6.2, the
diagonal "wrapped" after N columns. You can have this behavior
with this option. This affects only tall matrices.
See also
--------
diag_indices, diag_indices_from
Notes
-----
.. versionadded:: 1.4.0
This functionality can be obtained via `diag_indices`, but internally
this version uses a much faster implementation that never constructs the
indices and uses simple slicing.
Examples
--------
>>> import numpy as np
>>> a = np.zeros((3, 3), int)
>>> np.fill_diagonal(a, 5)
>>> a
array([[5, 0, 0],
[0, 5, 0],
[0, 0, 5]])
The same function can operate on a 4-D array:
>>> a = np.zeros((3, 3, 3, 3), int)
>>> np.fill_diagonal(a, 4)
We only show a few blocks for clarity:
>>> a[0, 0]
array([[4, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a[1, 1]
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 0]])
>>> a[2, 2]
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 4]])
The wrap option affects only tall matrices:
>>> # tall matrices no wrap
>>> a = np.zeros((5, 3), int)
>>> np.fill_diagonal(a, 4)
>>> a
array([[4, 0, 0],
[0, 4, 0],
[0, 0, 4],
[0, 0, 0],
[0, 0, 0]])
>>> # tall matrices wrap
>>> a = np.zeros((5, 3), int)
>>> np.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0],
[0, 4, 0],
[0, 0, 4],
[0, 0, 0],
[4, 0, 0]])
>>> # wide matrices
>>> a = np.zeros((3, 5), int)
>>> np.fill_diagonal(a, 4, wrap=True)
>>> a
array([[4, 0, 0, 0, 0],
[0, 4, 0, 0, 0],
[0, 0, 4, 0, 0]])
The anti-diagonal can be filled by reversing the order of elements
using either `numpy.flipud` or `numpy.fliplr`.
>>> a = np.zeros((3, 3), int);
>>> np.fill_diagonal(np.fliplr(a), [1,2,3]) # Horizontal flip
>>> a
array([[0, 0, 1],
[0, 2, 0],
[3, 0, 0]])
>>> np.fill_diagonal(np.flipud(a), [1,2,3]) # Vertical flip
>>> a
array([[0, 0, 3],
[0, 2, 0],
[1, 0, 0]])
Note that the order in which the diagonal is filled varies depending
on the flip function.
numpy.finfo
Python Library Documentation: class finfo in module numpy
class finfo(builtins.object)
| finfo(dtype)
|
| finfo(dtype)
|
| Machine limits for floating point types.
|
| Attributes
| ----------
| bits : int
| The number of bits occupied by the type.
| dtype : dtype
| Returns the dtype for which `finfo` returns information. For complex
| input, the returned dtype is the associated ``float*`` dtype for its
| real and complex components.
| eps : float
| The difference between 1.0 and the next smallest representable float
| larger than 1.0. For example, for 64-bit binary floats in the IEEE-754
| standard, ``eps = 2**-52``, approximately 2.22e-16.
| epsneg : float
| The difference between 1.0 and the next smallest representable float
| less than 1.0. For example, for 64-bit binary floats in the IEEE-754
| standard, ``epsneg = 2**-53``, approximately 1.11e-16.
| iexp : int
| The number of bits in the exponent portion of the floating point
| representation.
| machep : int
| The exponent that yields `eps`.
| max : floating point number of the appropriate type
| The largest representable number.
| maxexp : int
| The smallest positive power of the base (2) that causes overflow.
| min : floating point number of the appropriate type
| The smallest representable number, typically ``-max``.
| minexp : int
| The most negative power of the base (2) consistent with there
| being no leading 0's in the mantissa.
| negep : int
| The exponent that yields `epsneg`.
| nexp : int
| The number of bits in the exponent including its sign and bias.
| nmant : int
| The number of bits in the mantissa.
| precision : int
| The approximate number of decimal digits to which this kind of
| float is precise.
| resolution : floating point number of the appropriate type
| The approximate decimal resolution of this type, i.e.,
| ``10**-precision``.
| tiny : float
| An alias for `smallest_normal`, kept for backwards compatibility.
| smallest_normal : float
| The smallest positive floating point number with 1 as leading bit in
| the mantissa following IEEE-754 (see Notes).
| smallest_subnormal : float
| The smallest positive floating point number with 0 as leading bit in
| the mantissa following IEEE-754.
|
| Parameters
| ----------
| dtype : float, dtype, or instance
| Kind of floating point or complex floating point
| data-type about which to get information.
|
| See Also
| --------
| iinfo : The equivalent for integer data types.
| spacing : The distance between a value and the nearest adjacent number
| nextafter : The next floating point value after x1 towards x2
|
| Notes
| -----
| For developers of NumPy: do not instantiate this at the module level.
| The initial calculation of these parameters is expensive and negatively
| impacts import times. These objects are cached, so calling ``finfo()``
| repeatedly inside your functions is not a problem.
|
| Note that ``smallest_normal`` is not actually the smallest positive
| representable value in a NumPy floating point type. As in the IEEE-754
| standard [1]_, NumPy floating point types make use of subnormal numbers to
| fill the gap between 0 and ``smallest_normal``. However, subnormal numbers
| may have significantly reduced precision [2]_.
|
| This function can also be used for complex data types as well. If used,
| the output will be the same as the corresponding real float type
| (e.g. numpy.finfo(numpy.csingle) is the same as numpy.finfo(numpy.single)).
| However, the output is true for the real and imaginary components.
|
| References
| ----------
| .. [1] IEEE Standard for Floating-Point Arithmetic, IEEE Std 754-2008,
| pp.1-70, 2008, https://doi.org/10.1109/IEEESTD.2008.4610935
| .. [2] Wikipedia, "Denormal Numbers",
| https://en.wikipedia.org/wiki/Denormal_number
|
| Examples
| --------
| >>> import numpy as np
| >>> np.finfo(np.float64).dtype
| dtype('float64')
| >>> np.finfo(np.complex64).dtype
| dtype('float32')
|
| Methods defined here:
|
| __repr__(self) from numpy._core.getlimits.finfo
| Return repr(self).
|
| __str__(self) from numpy._core.getlimits.finfo
| Return str(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, dtype) from numpy._core.getlimits.finfo
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| smallest_normal
| Return the value for the smallest normal.
|
| Returns
| -------
| smallest_normal : float
| Value for the smallest normal.
|
| Warns
| -----
| UserWarning
| If the calculated value for the smallest normal is requested for
| double-double.
|
| tiny
| Return the value for tiny, alias of smallest_normal.
|
| Returns
| -------
| tiny : float
| Value for the smallest normal, alias of smallest_normal.
|
| Warns
| -----
| UserWarning
| If the calculated value for the smallest normal is requested for
| double-double.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
numpy.fix
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
fix(x, out=None)
Round to nearest integer towards zero.
Round an array of floats element-wise to nearest integer towards zero.
The rounded values have the same data-type as the input.
Parameters
----------
x : array_like
An array to be rounded
out : ndarray, optional
A location into which the result is stored. If provided, it must have
a shape that the input broadcasts to. If not provided or None, a
freshly-allocated array is returned.
Returns
-------
out : ndarray of floats
An array with the same dimensions and data-type as the input.
If second argument is not supplied then a new array is returned
with the rounded values.
If a second argument is supplied the result is stored there.
The return value ``out`` is then a reference to that array.
See Also
--------
rint, trunc, floor, ceil
around : Round to given number of decimals
Examples
--------
>>> import numpy as np
>>> np.fix(3.14)
3.0
>>> np.fix(3)
3
>>> np.fix([2.1, 2.9, -2.1, -2.9])
array([ 2., 2., -2., -2.])
numpy.flatiter
Python Library Documentation: class flatiter in module numpy class flatiter(builtins.object) | Flat iterator object to iterate over arrays. | | A `flatiter` iterator is returned by ``x.flat`` for any array `x`. | It allows iterating over the array as if it were a 1-D array, | either in a for-loop or by calling its `next` method. | | Iteration is done in row-major, C-style order (the last | index varying the fastest). The iterator can also be indexed using | basic slicing or advanced indexing. | | See Also | -------- | ndarray.flat : Return a flat iterator over an array. | ndarray.flatten : Returns a flattened copy of an array. | | Notes | ----- | A `flatiter` iterator can not be constructed directly from Python code | by calling the `flatiter` constructor. | | Examples | -------- | >>> import numpy as np | >>> x = np.arange(6).reshape(2, 3) | >>> fl = x.flat | >>> type(fl) | <class 'numpy.flatiter'> | >>> for item in fl: | ... print(item) | ... | 0 | 1 | 2 | 3 | 4 | 5 | | >>> fl[2:4] | array([2, 3]) | | Methods defined here: | | __array__(...) | __array__(type=None) Get array from iterator | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __next__(self, /) | Implement next(self). | | __setitem__(self, key, value, /) | Set self[key] to value. | | copy(...) | copy() | | Get a copy of the iterator as a 1-D array. | | Examples | -------- | >>> import numpy as np | >>> x = np.arange(6).reshape(2, 3) | >>> x | array([[0, 1, 2], | [3, 4, 5]]) | >>> fl = x.flat | >>> fl.copy() | array([0, 1, 2, 3, 4, 5]) | | ---------------------------------------------------------------------- | Data descriptors defined here: | | base | A reference to the array that is iterated over. | | Examples | -------- | >>> import numpy as np | >>> x = np.arange(5) | >>> fl = x.flat | >>> fl.base is x | True | | coords | An N-dimensional tuple of current coordinates. | | Examples | -------- | >>> import numpy as np | >>> x = np.arange(6).reshape(2, 3) | >>> fl = x.flat | >>> fl.coords | (0, 0) | >>> next(fl) | 0 | >>> fl.coords | (0, 1) | | index | Current flat index into the array. | | Examples | -------- | >>> import numpy as np | >>> x = np.arange(6).reshape(2, 3) | >>> fl = x.flat | >>> fl.index | 0 | >>> next(fl) | 0 | >>> fl.index | 1 | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
numpy.flatnonzero
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
flatnonzero(a)
Return indices that are non-zero in the flattened version of a.
This is equivalent to ``np.nonzero(np.ravel(a))[0]``.
Parameters
----------
a : array_like
Input data.
Returns
-------
res : ndarray
Output array, containing the indices of the elements of ``a.ravel()``
that are non-zero.
See Also
--------
nonzero : Return the indices of the non-zero elements of the input array.
ravel : Return a 1-D array containing the elements of the input array.
Examples
--------
>>> import numpy as np
>>> x = np.arange(-2, 3)
>>> x
array([-2, -1, 0, 1, 2])
>>> np.flatnonzero(x)
array([0, 1, 3, 4])
Use the indices of the non-zero elements as an index array to extract
these elements:
>>> x.ravel()[np.flatnonzero(x)]
array([-2, -1, 1, 2])
numpy.flexible
Python Library Documentation: class flexible in module numpy class flexible(generic) | Abstract base class of all scalar types without predefined length. | The actual size of these types depends on the specific `numpy.dtype` | instantiation. | | Method resolution order: | flexible | generic | builtins.object | | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Data and other attributes inherited from generic: | | __hash__ = None
numpy.flip
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
flip(m, axis=None)
Reverse the order of elements in an array along the given axis.
The shape of the array is preserved, but the elements are reordered.
.. versionadded:: 1.12.0
Parameters
----------
m : array_like
Input array.
axis : None or int or tuple of ints, optional
Axis or axes along which to flip over. The default,
axis=None, will flip over all of the axes of the input array.
If axis is negative it counts from the last to the first axis.
If axis is a tuple of ints, flipping is performed on all of the axes
specified in the tuple.
.. versionchanged:: 1.15.0
None and tuples of axes are supported
Returns
-------
out : array_like
A view of `m` with the entries of axis reversed. Since a view is
returned, this operation is done in constant time.
See Also
--------
flipud : Flip an array vertically (axis=0).
fliplr : Flip an array horizontally (axis=1).
Notes
-----
flip(m, 0) is equivalent to flipud(m).
flip(m, 1) is equivalent to fliplr(m).
flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at position n.
flip(m) corresponds to ``m[::-1,::-1,...,::-1]`` with ``::-1`` at all
positions.
flip(m, (0, 1)) corresponds to ``m[::-1,::-1,...]`` with ``::-1`` at
position 0 and position 1.
Examples
--------
>>> import numpy as np
>>> A = np.arange(8).reshape((2,2,2))
>>> A
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.flip(A, 0)
array([[[4, 5],
[6, 7]],
[[0, 1],
[2, 3]]])
>>> np.flip(A, 1)
array([[[2, 3],
[0, 1]],
[[6, 7],
[4, 5]]])
>>> np.flip(A)
array([[[7, 6],
[5, 4]],
[[3, 2],
[1, 0]]])
>>> np.flip(A, (0, 2))
array([[[5, 4],
[7, 6]],
[[1, 0],
[3, 2]]])
>>> rng = np.random.default_rng()
>>> A = rng.normal(size=(3,4,5))
>>> np.all(np.flip(A,2) == A[:,:,::-1,...])
True
numpy.fliplr
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
fliplr(m)
Reverse the order of elements along axis 1 (left/right).
For a 2-D array, this flips the entries in each row in the left/right
direction. Columns are preserved, but appear in a different order than
before.
Parameters
----------
m : array_like
Input array, must be at least 2-D.
Returns
-------
f : ndarray
A view of `m` with the columns reversed. Since a view
is returned, this operation is :math:`\mathcal O(1)`.
See Also
--------
flipud : Flip array in the up/down direction.
flip : Flip array in one or more dimensions.
rot90 : Rotate array counterclockwise.
Notes
-----
Equivalent to ``m[:,::-1]`` or ``np.flip(m, axis=1)``.
Requires the array to be at least 2-D.
Examples
--------
>>> import numpy as np
>>> A = np.diag([1.,2.,3.])
>>> A
array([[1., 0., 0.],
[0., 2., 0.],
[0., 0., 3.]])
>>> np.fliplr(A)
array([[0., 0., 1.],
[0., 2., 0.],
[3., 0., 0.]])
>>> rng = np.random.default_rng()
>>> A = rng.normal(size=(2,3,5))
>>> np.all(np.fliplr(A) == A[:,::-1,...])
True
numpy.flipud
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
flipud(m)
Reverse the order of elements along axis 0 (up/down).
For a 2-D array, this flips the entries in each column in the up/down
direction. Rows are preserved, but appear in a different order than before.
Parameters
----------
m : array_like
Input array.
Returns
-------
out : array_like
A view of `m` with the rows reversed. Since a view is
returned, this operation is :math:`\mathcal O(1)`.
See Also
--------
fliplr : Flip array in the left/right direction.
flip : Flip array in one or more dimensions.
rot90 : Rotate array counterclockwise.
Notes
-----
Equivalent to ``m[::-1, ...]`` or ``np.flip(m, axis=0)``.
Requires the array to be at least 1-D.
Examples
--------
>>> import numpy as np
>>> A = np.diag([1.0, 2, 3])
>>> A
array([[1., 0., 0.],
[0., 2., 0.],
[0., 0., 3.]])
>>> np.flipud(A)
array([[0., 0., 3.],
[0., 2., 0.],
[1., 0., 0.]])
>>> rng = np.random.default_rng()
>>> A = rng.normal(size=(2,3,5))
>>> np.all(np.flipud(A) == A[::-1,...])
True
>>> np.flipud([1,2])
array([2, 1])
numpy.float16
Python Library Documentation: class float16 in module numpy class float16(floating) | Half-precision floating-point number type. | | :Character code: ``'e'`` | :Canonical name: `numpy.half` | :Alias on this platform (win32 AMD64): `numpy.float16`: 16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa. | | Method resolution order: | float16 | floating | inexact | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | as_integer_ratio(...) | half.as_integer_ratio() -> (int, int) | | Return a pair of integers, whose ratio is exactly equal to the original | floating point number, and with a positive denominator. | Raise `OverflowError` on infinities and a `ValueError` on NaNs. | | >>> np.half(10.0).as_integer_ratio() | (10, 1) | >>> np.half(0.0).as_integer_ratio() | (0, 1) | >>> np.half(-.25).as_integer_ratio() | (-1, 4) | | is_integer(...) | half.is_integer() -> bool | | Return ``True`` if the floating point number is finite with integral | value, and ``False`` otherwise. | | .. versionadded:: 1.22 | | Examples | -------- | >>> np.half(-2.0).is_integer() | True | >>> np.half(3.2).is_integer() | False | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from floating: | | __round__(...) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __reduce__(...) | Helper for pickle. | | __rlshift__(self, value, /) | Return value<<self. | | __ror__(self, value, /) | Return value|self. | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.float32
Python Library Documentation: class float32 in module numpy class float32(floating) | Single-precision floating-point number type, compatible with C ``float``. | | :Character code: ``'f'`` | :Canonical name: `numpy.single` | :Alias on this platform (win32 AMD64): `numpy.float32`: 32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa. | | Method resolution order: | float32 | floating | inexact | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | as_integer_ratio(...) | single.as_integer_ratio() -> (int, int) | | Return a pair of integers, whose ratio is exactly equal to the original | floating point number, and with a positive denominator. | Raise `OverflowError` on infinities and a `ValueError` on NaNs. | | >>> np.single(10.0).as_integer_ratio() | (10, 1) | >>> np.single(0.0).as_integer_ratio() | (0, 1) | >>> np.single(-.25).as_integer_ratio() | (-1, 4) | | is_integer(...) | single.is_integer() -> bool | | Return ``True`` if the floating point number is finite with integral | value, and ``False`` otherwise. | | .. versionadded:: 1.22 | | Examples | -------- | >>> np.single(-2.0).is_integer() | True | >>> np.single(3.2).is_integer() | False | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from floating: | | __round__(...) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __reduce__(...) | Helper for pickle. | | __rlshift__(self, value, /) | Return value<<self. | | __ror__(self, value, /) | Return value|self. | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.float64
Python Library Documentation: class float64 in module numpy
class float64(floating, builtins.float)
| float64(x=0, /)
|
| Double-precision floating-point number type, compatible with Python
| :class:`float` and C ``double``.
|
| :Character code: ``'d'``
| :Canonical name: `numpy.double`
| :Alias on this platform (win32 AMD64): `numpy.float64`: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa.
|
| Method resolution order:
| float64
| floating
| inexact
| number
| generic
| builtins.float
| builtins.object
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| as_integer_ratio(...)
| double.as_integer_ratio() -> (int, int)
|
| Return a pair of integers, whose ratio is exactly equal to the original
| floating point number, and with a positive denominator.
| Raise `OverflowError` on infinities and a `ValueError` on NaNs.
|
| >>> np.double(10.0).as_integer_ratio()
| (10, 1)
| >>> np.double(0.0).as_integer_ratio()
| (0, 1)
| >>> np.double(-.25).as_integer_ratio()
| (-1, 4)
|
| is_integer(...)
| double.is_integer() -> bool
|
| Return ``True`` if the floating point number is finite with integral
| value, and ``False`` otherwise.
|
| .. versionadded:: 1.22
|
| Examples
| --------
| >>> np.double(-2.0).is_integer()
| True
| >>> np.double(3.2).is_integer()
| False
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| __class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.number` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.number` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.signedinteger[Any]
| numpy.signedinteger[typing.Any]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from floating:
|
| __round__(...)
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __format__(...)
| NumPy array scalar formatter
|
| __getitem__(self, key, /)
| Return self[key].
|
| __invert__(self, /)
| ~self
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __or__(self, value, /)
| Return self|value.
|
| __rand__(self, value, /)
| Return value&self.
|
| __reduce__(...)
| Helper for pickle.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setstate__(...)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| base
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.base`.
|
| data
| Pointer to start of data.
|
| device
|
| dtype
| Get array data-descriptor.
|
| flags
| The integer value of flags.
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.float:
|
| __ceil__(self, /)
| Return the ceiling as an Integral.
|
| __floor__(self, /)
| Return the floor as an Integral.
|
| __getnewargs__(self, /)
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> 3.14159.hex()
| '0x1.921f9f01b866ep+1'
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.float:
|
| __getformat__(typestr, /)
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
| little-endian' best describes the format of floating-point numbers used by the
| C type named by typestr.
|
| fromhex(string, /)
| Create a floating-point number from a hexadecimal string.
|
| >>> float.fromhex('0x1.ffffp10')
| 2047.984375
| >>> float.fromhex('-0x1p-1074')
| -5e-324
numpy.float_power
Python Library Documentation: ufunc
float_power = <ufunc 'float_power'>
float_power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
First array elements raised to powers from second array, element-wise.
Raise each base in `x1` to the positionally-corresponding power in `x2`.
`x1` and `x2` must be broadcastable to the same shape. This differs from
the power function in that integers, float16, and float32 are promoted to
floats with a minimum precision of float64 so that the result is always
inexact. The intent is that the function will return a usable result for
negative powers and seldom overflow for positive powers.
Negative values raised to a non-integral value will return ``nan``.
To get complex results, cast the input to complex, or specify the
``dtype`` to be ``complex`` (see the example below).
.. versionadded:: 1.12.0
Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
power : power function that preserves type
Examples
--------
>>> import numpy as np
Cube each element in a list.
>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.float_power(x1, 3)
array([ 0., 1., 8., 27., 64., 125.])
Raise the bases to different exponents.
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.float_power(x1, x2)
array([ 0., 1., 8., 27., 16., 5.])
The effect of broadcasting.
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.float_power(x1, x2)
array([[ 0., 1., 8., 27., 16., 5.],
[ 0., 1., 8., 27., 16., 5.]])
Negative values raised to a non-integral value will result in ``nan``
(and a warning will be generated).
>>> x3 = np.array([-1, -4])
>>> with np.errstate(invalid='ignore'):
... p = np.float_power(x3, 1.5)
...
>>> p
array([nan, nan])
To get complex results, give the argument ``dtype=complex``.
>>> np.float_power(x3, 1.5, dtype=complex)
array([-1.83697020e-16-1.j, -1.46957616e-15-8.j])
numpy.floating
Python Library Documentation: class floating in module numpy class floating(inexact) | Abstract base class of all floating-point scalar types. | | Method resolution order: | floating | inexact | number | generic | builtins.object | | Methods defined here: | | __round__(...) | | ---------------------------------------------------------------------- | Class methods inherited from number: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Data and other attributes inherited from generic: | | __hash__ = None
numpy.floor
Python Library Documentation: ufunc
floor = <ufunc 'floor'>
floor(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the floor of the input, element-wise.
The floor of the scalar `x` is the largest integer `i`, such that
`i <= x`. It is often denoted as :math:`\lfloor x \rfloor`.
Parameters
----------
x : array_like
Input data.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The floor of each element in `x`.
This is a scalar if `x` is a scalar.
See Also
--------
ceil, trunc, rint, fix
Notes
-----
Some spreadsheet programs calculate the "floor-towards-zero", where
``floor(-2.5) == -2``. NumPy instead uses the definition of
`floor` where `floor(-2.5) == -3`. The "floor-towards-zero"
function is called ``fix`` in NumPy.
Examples
--------
>>> import numpy as np
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.floor(a)
array([-2., -2., -1., 0., 1., 1., 2.])
numpy.floor_divide
Python Library Documentation: ufunc
floor_divide = <ufunc 'floor_divide'>
floor_divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the largest integer smaller or equal to the division of the inputs.
It is equivalent to the Python ``//`` operator and pairs with the
Python ``%`` (`remainder`), function so that ``a = a % b + b * (a // b)``
up to roundoff.
Parameters
----------
x1 : array_like
Numerator.
x2 : array_like
Denominator.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
y = floor(`x1`/`x2`)
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
remainder : Remainder complementary to floor_divide.
divmod : Simultaneous floor division and remainder.
divide : Standard division.
floor : Round a number to the nearest integer toward minus infinity.
ceil : Round a number to the nearest integer toward infinity.
Examples
--------
>>> import numpy as np
>>> np.floor_divide(7,3)
2
>>> np.floor_divide([1., 2., 3., 4.], 2.5)
array([ 0., 0., 1., 1.])
The ``//`` operator can be used as a shorthand for ``np.floor_divide``
on ndarrays.
>>> x1 = np.array([1., 2., 3., 4.])
>>> x1 // 2.5
array([0., 0., 1., 1.])
numpy.fmax
Python Library Documentation: ufunc
fmax = <ufunc 'fmax'>
fmax(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Element-wise maximum of array elements.
Compare two arrays and return a new array containing the element-wise
maxima. If one of the elements being compared is a NaN, then the
non-nan element is returned. If both elements are NaNs then the first
is returned. The latter distinction is important for complex NaNs,
which are defined as at least one of the real or imaginary parts being
a NaN. The net effect is that NaNs are ignored when possible.
Parameters
----------
x1, x2 : array_like
The arrays holding the elements to be compared.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The maximum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
fmin :
Element-wise minimum of two arrays, ignores NaNs.
maximum :
Element-wise maximum of two arrays, propagates NaNs.
amax :
The maximum value of an array along a given axis, propagates NaNs.
nanmax :
The maximum value of an array along a given axis, ignores NaNs.
minimum, amin, nanmin
Notes
-----
.. versionadded:: 1.3.0
The fmax is equivalent to ``np.where(x1 >= x2, x1, x2)`` when neither
x1 nor x2 are NaNs, but it is faster and does proper broadcasting.
Examples
--------
>>> import numpy as np
>>> np.fmax([2, 3, 4], [1, 5, 2])
array([ 2., 5., 4.])
>>> np.fmax(np.eye(2), [0.5, 2])
array([[ 1. , 2. ],
[ 0.5, 2. ]])
>>> np.fmax([np.nan, 0, np.nan],[0, np.nan, np.nan])
array([ 0., 0., nan])
numpy.fmin
Python Library Documentation: ufunc
fmin = <ufunc 'fmin'>
fmin(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Element-wise minimum of array elements.
Compare two arrays and return a new array containing the element-wise
minima. If one of the elements being compared is a NaN, then the
non-nan element is returned. If both elements are NaNs then the first
is returned. The latter distinction is important for complex NaNs,
which are defined as at least one of the real or imaginary parts being
a NaN. The net effect is that NaNs are ignored when possible.
Parameters
----------
x1, x2 : array_like
The arrays holding the elements to be compared.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The minimum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
fmax :
Element-wise maximum of two arrays, ignores NaNs.
minimum :
Element-wise minimum of two arrays, propagates NaNs.
amin :
The minimum value of an array along a given axis, propagates NaNs.
nanmin :
The minimum value of an array along a given axis, ignores NaNs.
maximum, amax, nanmax
Notes
-----
.. versionadded:: 1.3.0
The fmin is equivalent to ``np.where(x1 <= x2, x1, x2)`` when neither
x1 nor x2 are NaNs, but it is faster and does proper broadcasting.
Examples
--------
>>> import numpy as np
>>> np.fmin([2, 3, 4], [1, 5, 2])
array([1, 3, 2])
>>> np.fmin(np.eye(2), [0.5, 2])
array([[ 0.5, 0. ],
[ 0. , 1. ]])
>>> np.fmin([np.nan, 0, np.nan],[0, np.nan, np.nan])
array([ 0., 0., nan])
numpy.fmod
Python Library Documentation: ufunc
fmod = <ufunc 'fmod'>
fmod(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns the element-wise remainder of division.
This is the NumPy implementation of the C library function fmod, the
remainder has the same sign as the dividend `x1`. It is equivalent to
the Matlab(TM) ``rem`` function and should not be confused with the
Python modulus operator ``x1 % x2``.
Parameters
----------
x1 : array_like
Dividend.
x2 : array_like
Divisor.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : array_like
The remainder of the division of `x1` by `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
remainder : Equivalent to the Python ``%`` operator.
divide
Notes
-----
The result of the modulo operation for negative dividend and divisors
is bound by conventions. For `fmod`, the sign of result is the sign of
the dividend, while for `remainder` the sign of the result is the sign
of the divisor. The `fmod` function is equivalent to the Matlab(TM)
``rem`` function.
Examples
--------
>>> import numpy as np
>>> np.fmod([-3, -2, -1, 1, 2, 3], 2)
array([-1, 0, -1, 1, 0, 1])
>>> np.remainder([-3, -2, -1, 1, 2, 3], 2)
array([1, 0, 1, 1, 0, 1])
>>> np.fmod([5, 3], [2, 2.])
array([ 1., 1.])
>>> a = np.arange(-3, 3).reshape(3, 2)
>>> a
array([[-3, -2],
[-1, 0],
[ 1, 2]])
>>> np.fmod(a, [2,2])
array([[-1, 0],
[-1, 0],
[ 1, 0]])
numpy.format_float_positional
Python Library Documentation: function format_float_positional in module numpy
format_float_positional(x, precision=None, unique=True, fractional=True, trim='k', sign=False, pad_left=None, pad_right=None, min_digits=None)
Format a floating-point scalar as a decimal string in positional notation.
Provides control over rounding, trimming and padding. Uses and assumes
IEEE unbiased rounding. Uses the "Dragon4" algorithm.
Parameters
----------
x : python float or numpy floating scalar
Value to format.
precision : non-negative integer or None, optional
Maximum number of digits to print. May be None if `unique` is
`True`, but must be an integer if unique is `False`.
unique : boolean, optional
If `True`, use a digit-generation strategy which gives the shortest
representation which uniquely identifies the floating-point number from
other values of the same type, by judicious rounding. If `precision`
is given fewer digits than necessary can be printed, or if `min_digits`
is given more can be printed, in which cases the last digit is rounded
with unbiased rounding.
If `False`, digits are generated as if printing an infinite-precision
value and stopping after `precision` digits, rounding the remaining
value with unbiased rounding
fractional : boolean, optional
If `True`, the cutoffs of `precision` and `min_digits` refer to the
total number of digits after the decimal point, including leading
zeros.
If `False`, `precision` and `min_digits` refer to the total number of
significant digits, before or after the decimal point, ignoring leading
zeros.
trim : one of 'k', '.', '0', '-', optional
Controls post-processing trimming of trailing digits, as follows:
* 'k' : keep trailing zeros, keep decimal point (no trimming)
* '.' : trim all trailing zeros, leave decimal point
* '0' : trim all but the zero before the decimal point. Insert the
zero if it is missing.
* '-' : trim trailing zeros and any trailing decimal point
sign : boolean, optional
Whether to show the sign for positive values.
pad_left : non-negative integer, optional
Pad the left side of the string with whitespace until at least that
many characters are to the left of the decimal point.
pad_right : non-negative integer, optional
Pad the right side of the string with whitespace until at least that
many characters are to the right of the decimal point.
min_digits : non-negative integer or None, optional
Minimum number of digits to print. Only has an effect if `unique=True`
in which case additional digits past those necessary to uniquely
identify the value may be printed, rounding the last additional digit.
.. versionadded:: 1.21.0
Returns
-------
rep : string
The string representation of the floating point value
See Also
--------
format_float_scientific
Examples
--------
>>> import numpy as np
>>> np.format_float_positional(np.float32(np.pi))
'3.1415927'
>>> np.format_float_positional(np.float16(np.pi))
'3.14'
>>> np.format_float_positional(np.float16(0.3))
'0.3'
>>> np.format_float_positional(np.float16(0.3), unique=False, precision=10)
'0.3000488281'
numpy.format_float_scientific
Python Library Documentation: function format_float_scientific in module numpy
format_float_scientific(x, precision=None, unique=True, trim='k', sign=False, pad_left=None, exp_digits=None, min_digits=None)
Format a floating-point scalar as a decimal string in scientific notation.
Provides control over rounding, trimming and padding. Uses and assumes
IEEE unbiased rounding. Uses the "Dragon4" algorithm.
Parameters
----------
x : python float or numpy floating scalar
Value to format.
precision : non-negative integer or None, optional
Maximum number of digits to print. May be None if `unique` is
`True`, but must be an integer if unique is `False`.
unique : boolean, optional
If `True`, use a digit-generation strategy which gives the shortest
representation which uniquely identifies the floating-point number from
other values of the same type, by judicious rounding. If `precision`
is given fewer digits than necessary can be printed. If `min_digits`
is given more can be printed, in which cases the last digit is rounded
with unbiased rounding.
If `False`, digits are generated as if printing an infinite-precision
value and stopping after `precision` digits, rounding the remaining
value with unbiased rounding
trim : one of 'k', '.', '0', '-', optional
Controls post-processing trimming of trailing digits, as follows:
* 'k' : keep trailing zeros, keep decimal point (no trimming)
* '.' : trim all trailing zeros, leave decimal point
* '0' : trim all but the zero before the decimal point. Insert the
zero if it is missing.
* '-' : trim trailing zeros and any trailing decimal point
sign : boolean, optional
Whether to show the sign for positive values.
pad_left : non-negative integer, optional
Pad the left side of the string with whitespace until at least that
many characters are to the left of the decimal point.
exp_digits : non-negative integer, optional
Pad the exponent with zeros until it contains at least this
many digits. If omitted, the exponent will be at least 2 digits.
min_digits : non-negative integer or None, optional
Minimum number of digits to print. This only has an effect for
`unique=True`. In that case more digits than necessary to uniquely
identify the value may be printed and rounded unbiased.
.. versionadded:: 1.21.0
Returns
-------
rep : string
The string representation of the floating point value
See Also
--------
format_float_positional
Examples
--------
>>> import numpy as np
>>> np.format_float_scientific(np.float32(np.pi))
'3.1415927e+00'
>>> s = np.float32(1.23e24)
>>> np.format_float_scientific(s, unique=False, precision=15)
'1.230000071797338e+24'
>>> np.format_float_scientific(s, exp_digits=4)
'1.23e+0024'
numpy.frexp
Python Library Documentation: ufunc
frexp = <ufunc 'frexp'>
frexp(x[, out1, out2], / [, out=(None, None)], *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Decompose the elements of x into mantissa and twos exponent.
Returns (`mantissa`, `exponent`), where ``x = mantissa * 2**exponent``.
The mantissa lies in the open interval(-1, 1), while the twos
exponent is a signed integer.
Parameters
----------
x : array_like
Array of numbers to be decomposed.
out1 : ndarray, optional
Output array for the mantissa. Must have the same shape as `x`.
out2 : ndarray, optional
Output array for the exponent. Must have the same shape as `x`.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
mantissa : ndarray
Floating values between -1 and 1.
This is a scalar if `x` is a scalar.
exponent : ndarray
Integer exponents of 2.
This is a scalar if `x` is a scalar.
See Also
--------
ldexp : Compute ``y = x1 * 2**x2``, the inverse of `frexp`.
Notes
-----
Complex dtypes are not supported, they will raise a TypeError.
Examples
--------
>>> import numpy as np
>>> x = np.arange(9)
>>> y1, y2 = np.frexp(x)
>>> y1
array([ 0. , 0.5 , 0.5 , 0.75 , 0.5 , 0.625, 0.75 , 0.875,
0.5 ])
>>> y2
array([0, 1, 2, 2, 3, 3, 3, 3, 4])
>>> y1 * 2**y2
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8.])
numpy.from_dlpack
Python Library Documentation: built-in function from_dlpack in module numpy
from_dlpack(...)
from_dlpack(x, /, *, device=None, copy=None)
Create a NumPy array from an object implementing the ``__dlpack__``
protocol. Generally, the returned NumPy array is a read-only view
of the input object. See [1]_ and [2]_ for more details.
Parameters
----------
x : object
A Python object that implements the ``__dlpack__`` and
``__dlpack_device__`` methods.
device : device, optional
Device on which to place the created array. Default: ``None``.
Must be ``"cpu"`` if passed which may allow importing an array
that is not already CPU available.
copy : bool, optional
Boolean indicating whether or not to copy the input. If ``True``,
the copy will be made. If ``False``, the function will never copy,
and will raise ``BufferError`` in case a copy is deemed necessary.
Passing it requests a copy from the exporter who may or may not
implement the capability.
If ``None``, the function will reuse the existing memory buffer if
possible and copy otherwise. Default: ``None``.
Returns
-------
out : ndarray
References
----------
.. [1] Array API documentation,
https://data-apis.org/array-api/latest/design_topics/data_interchange.html#syntax-for-data-interchange-with-dlpack
.. [2] Python specification for DLPack,
https://dmlc.github.io/dlpack/latest/python_spec.html
Examples
--------
>>> import torch # doctest: +SKIP
>>> x = torch.arange(10) # doctest: +SKIP
>>> # create a view of the torch tensor "x" in NumPy
>>> y = np.from_dlpack(x) # doctest: +SKIP
numpy.frombuffer
Python Library Documentation: built-in function frombuffer in module numpy
frombuffer(...)
frombuffer(buffer, dtype=float, count=-1, offset=0, *, like=None)
Interpret a buffer as a 1-dimensional array.
Parameters
----------
buffer : buffer_like
An object that exposes the buffer interface.
dtype : data-type, optional
Data-type of the returned array; default: float.
count : int, optional
Number of items to read. ``-1`` means all data in the buffer.
offset : int, optional
Start reading the buffer from this offset (in bytes); default: 0.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
See also
--------
ndarray.tobytes
Inverse of this operation, construct Python bytes from the raw data
bytes in the array.
Notes
-----
If the buffer has data that is not in machine byte-order, this should
be specified as part of the data-type, e.g.::
>>> dt = np.dtype(int)
>>> dt = dt.newbyteorder('>')
>>> np.frombuffer(buf, dtype=dt) # doctest: +SKIP
The data of the resulting array will not be byteswapped, but will be
interpreted correctly.
This function creates a view into the original object. This should be safe
in general, but it may make sense to copy the result when the original
object is mutable or untrusted.
Examples
--------
>>> import numpy as np
>>> s = b'hello world'
>>> np.frombuffer(s, dtype='S1', count=5, offset=6)
array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')
>>> np.frombuffer(b'\x01\x02', dtype=np.uint8)
array([1, 2], dtype=uint8)
>>> np.frombuffer(b'\x01\x02\x03\x04\x05', dtype=np.uint8, count=3)
array([1, 2, 3], dtype=uint8)
numpy.fromfile
Python Library Documentation: built-in function fromfile in module numpy
fromfile(...)
fromfile(file, dtype=float, count=-1, sep='', offset=0, *, like=None)
Construct an array from data in a text or binary file.
A highly efficient way of reading binary data with a known data-type,
as well as parsing simply formatted text files. Data written using the
`tofile` method can be read using this function.
Parameters
----------
file : file or str or Path
Open file object or filename.
.. versionchanged:: 1.17.0
`pathlib.Path` objects are now accepted.
dtype : data-type
Data type of the returned array.
For binary files, it is used to determine the size and byte-order
of the items in the file.
Most builtin numeric types are supported and extension types may be supported.
.. versionadded:: 1.18.0
Complex dtypes.
count : int
Number of items to read. ``-1`` means all items (i.e., the complete
file).
sep : str
Separator between items if file is a text file.
Empty ("") separator means the file should be treated as binary.
Spaces (" ") in the separator match zero or more whitespace characters.
A separator consisting only of spaces must match at least one
whitespace.
offset : int
The offset (in bytes) from the file's current position. Defaults to 0.
Only permitted for binary files.
.. versionadded:: 1.17.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
See also
--------
load, save
ndarray.tofile
loadtxt : More flexible way of loading data from a text file.
Notes
-----
Do not rely on the combination of `tofile` and `fromfile` for
data storage, as the binary files generated are not platform
independent. In particular, no byte-order or data-type information is
saved. Data can be stored in the platform independent ``.npy`` format
using `save` and `load` instead.
Examples
--------
Construct an ndarray:
>>> import numpy as np
>>> dt = np.dtype([('time', [('min', np.int64), ('sec', np.int64)]),
... ('temp', float)])
>>> x = np.zeros((1,), dtype=dt)
>>> x['time']['min'] = 10; x['temp'] = 98.25
>>> x
array([((10, 0), 98.25)],
dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
Save the raw data to disk:
>>> import tempfile
>>> fname = tempfile.mkstemp()[1]
>>> x.tofile(fname)
Read the raw data from disk:
>>> np.fromfile(fname, dtype=dt)
array([((10, 0), 98.25)],
dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
The recommended way to store and load data:
>>> np.save(fname, x)
>>> np.load(fname + '.npy')
array([((10, 0), 98.25)],
dtype=[('time', [('min', '<i8'), ('sec', '<i8')]), ('temp', '<f8')])
numpy.fromfunction
Python Library Documentation: function fromfunction in module numpy
fromfunction(function, shape, *, dtype=<class 'float'>, like=None, **kwargs)
Construct an array by executing a function over each coordinate.
The resulting array therefore has a value ``fn(x, y, z)`` at
coordinate ``(x, y, z)``.
Parameters
----------
function : callable
The function is called with N parameters, where N is the rank of
`shape`. Each parameter represents the coordinates of the array
varying along a specific axis. For example, if `shape`
were ``(2, 2)``, then the parameters would be
``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
shape : (N,) tuple of ints
Shape of the output array, which also determines the shape of
the coordinate arrays passed to `function`.
dtype : data-type, optional
Data-type of the coordinate arrays passed to `function`.
By default, `dtype` is float.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
fromfunction : any
The result of the call to `function` is passed back directly.
Therefore the shape of `fromfunction` is completely determined by
`function`. If `function` returns a scalar value, the shape of
`fromfunction` would not match the `shape` parameter.
See Also
--------
indices, meshgrid
Notes
-----
Keywords other than `dtype` and `like` are passed to `function`.
Examples
--------
>>> import numpy as np
>>> np.fromfunction(lambda i, j: i, (2, 2), dtype=float)
array([[0., 0.],
[1., 1.]])
>>> np.fromfunction(lambda i, j: j, (2, 2), dtype=float)
array([[0., 1.],
[0., 1.]])
>>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
array([[ True, False, False],
[False, True, False],
[False, False, True]])
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
numpy.fromiter
Python Library Documentation: built-in function fromiter in module numpy
fromiter(...)
fromiter(iter, dtype, count=-1, *, like=None)
Create a new 1-dimensional array from an iterable object.
Parameters
----------
iter : iterable object
An iterable object providing data for the array.
dtype : data-type
The data-type of the returned array.
.. versionchanged:: 1.23
Object and subarray dtypes are now supported (note that the final
result is not 1-D for a subarray dtype).
count : int, optional
The number of items to read from *iterable*. The default is -1,
which means all data is read.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
The output array.
Notes
-----
Specify `count` to improve performance. It allows ``fromiter`` to
pre-allocate the output array, instead of resizing it on demand.
Examples
--------
>>> import numpy as np
>>> iterable = (x*x for x in range(5))
>>> np.fromiter(iterable, float)
array([ 0., 1., 4., 9., 16.])
A carefully constructed subarray dtype will lead to higher dimensional
results:
>>> iterable = ((x+1, x+2) for x in range(5))
>>> np.fromiter(iterable, dtype=np.dtype((int, 2)))
array([[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 6]])
numpy.frompyfunc
Python Library Documentation: built-in function frompyfunc in module numpy
frompyfunc(...)
frompyfunc(func, /, nin, nout, *[, identity])
Takes an arbitrary Python function and returns a NumPy ufunc.
Can be used, for example, to add broadcasting to a built-in Python
function (see Examples section).
Parameters
----------
func : Python function object
An arbitrary Python function.
nin : int
The number of input arguments.
nout : int
The number of objects returned by `func`.
identity : object, optional
The value to use for the `~numpy.ufunc.identity` attribute of the resulting
object. If specified, this is equivalent to setting the underlying
C ``identity`` field to ``PyUFunc_IdentityValue``.
If omitted, the identity is set to ``PyUFunc_None``. Note that this is
_not_ equivalent to setting the identity to ``None``, which implies the
operation is reorderable.
Returns
-------
out : ufunc
Returns a NumPy universal function (``ufunc``) object.
See Also
--------
vectorize : Evaluates pyfunc over input arrays using broadcasting rules of numpy.
Notes
-----
The returned ufunc always returns PyObject arrays.
Examples
--------
Use frompyfunc to add broadcasting to the Python function ``oct``:
>>> import numpy as np
>>> oct_array = np.frompyfunc(oct, 1, 1)
>>> oct_array(np.array((10, 30, 100)))
array(['0o12', '0o36', '0o144'], dtype=object)
>>> np.array((oct(10), oct(30), oct(100))) # for comparison
array(['0o12', '0o36', '0o144'], dtype='<U5')
numpy.fromregex
Python Library Documentation: function fromregex in module numpy
fromregex(file, regexp, dtype, encoding=None)
Construct an array from a text file, using regular expression parsing.
The returned array is always a structured array, and is constructed from
all matches of the regular expression in the file. Groups in the regular
expression are converted to fields of the structured array.
Parameters
----------
file : file, str, or pathlib.Path
Filename or file object to read.
.. versionchanged:: 1.22.0
Now accepts `os.PathLike` implementations.
regexp : str or regexp
Regular expression used to parse the file.
Groups in the regular expression correspond to fields in the dtype.
dtype : dtype or list of dtypes
Dtype for the structured array; must be a structured datatype.
encoding : str, optional
Encoding used to decode the inputfile. Does not apply to input streams.
.. versionadded:: 1.14.0
Returns
-------
output : ndarray
The output array, containing the part of the content of `file` that
was matched by `regexp`. `output` is always a structured array.
Raises
------
TypeError
When `dtype` is not a valid dtype for a structured array.
See Also
--------
fromstring, loadtxt
Notes
-----
Dtypes for structured arrays can be specified in several forms, but all
forms specify at least the data type and field name. For details see
`basics.rec`.
Examples
--------
>>> import numpy as np
>>> from io import StringIO
>>> text = StringIO("1312 foo\n1534 bar\n444 qux")
>>> regexp = r"(\d+)\s+(...)" # match [digits, whitespace, anything]
>>> output = np.fromregex(text, regexp,
... [('num', np.int64), ('key', 'S3')])
>>> output
array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')],
dtype=[('num', '<i8'), ('key', 'S3')])
>>> output['num']
array([1312, 1534, 444])
numpy.fromstring
Python Library Documentation: built-in function fromstring in module numpy
fromstring(...)
fromstring(string, dtype=float, count=-1, *, sep, like=None)
A new 1-D array initialized from text data in a string.
Parameters
----------
string : str
A string containing the data.
dtype : data-type, optional
The data type of the array; default: float. For binary input data,
the data must be in exactly this format. Most builtin numeric types are
supported and extension types may be supported.
.. versionadded:: 1.18.0
Complex dtypes.
count : int, optional
Read this number of `dtype` elements from the data. If this is
negative (the default), the count will be determined from the
length of the data.
sep : str, optional
The string separating numbers in the data; extra whitespace between
elements is also ignored.
.. deprecated:: 1.14
Passing ``sep=''``, the default, is deprecated since it will
trigger the deprecated binary mode of this function. This mode
interprets `string` as binary bytes, rather than ASCII text with
decimal numbers, an operation which is better spelt
``frombuffer(string, dtype, count)``. If `string` contains unicode
text, the binary mode of `fromstring` will first encode it into
bytes using utf-8, which will not produce sane results.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
arr : ndarray
The constructed array.
Raises
------
ValueError
If the string is not the correct size to satisfy the requested
`dtype` and `count`.
See Also
--------
frombuffer, fromfile, fromiter
Examples
--------
>>> import numpy as np
>>> np.fromstring('1 2', dtype=int, sep=' ')
array([1, 2])
>>> np.fromstring('1, 2', dtype=int, sep=',')
array([1, 2])
numpy.full
Python Library Documentation: function full in module numpy
full(shape, fill_value, dtype=None, order='C', *, device=None, like=None)
Return a new array of given shape and type, filled with `fill_value`.
Parameters
----------
shape : int or sequence of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
fill_value : scalar or array_like
Fill value.
dtype : data-type, optional
The desired data-type for the array The default, None, means
``np.array(fill_value).dtype``.
order : {'C', 'F'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory.
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
Array of `fill_value` with the given shape, dtype, and order.
See Also
--------
full_like : Return a new array with shape of input filled with value.
empty : Return a new uninitialized array.
ones : Return a new array setting values to one.
zeros : Return a new array setting values to zero.
Examples
--------
>>> import numpy as np
>>> np.full((2, 2), np.inf)
array([[inf, inf],
[inf, inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
[10, 10]])
>>> np.full((2, 2), [1, 2])
array([[1, 2],
[1, 2]])
numpy.full_like
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None, *, device=None)
Return a full array with the same shape and type as a given array.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of
the returned array.
fill_value : array_like
Fill value.
dtype : data-type, optional
Overrides the data type of the result.
order : {'C', 'F', 'A', or 'K'}, optional
Overrides the memory layout of the result. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'C' otherwise. 'K' means match the layout of `a` as closely
as possible.
subok : bool, 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.
shape : int 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.
.. versionadded:: 1.17.0
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
Array of `fill_value` with the same shape and type as `a`.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
zeros_like : Return an array of zeros with shape and type of input.
full : Return a new array of given shape filled with value.
Examples
--------
>>> import numpy as np
>>> x = np.arange(6, dtype=int)
>>> np.full_like(x, 1)
array([1, 1, 1, 1, 1, 1])
>>> np.full_like(x, 0.1)
array([0, 0, 0, 0, 0, 0])
>>> np.full_like(x, 0.1, dtype=np.double)
array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
>>> np.full_like(x, np.nan, dtype=np.double)
array([nan, nan, nan, nan, nan, nan])
>>> y = np.arange(6, dtype=np.double)
>>> np.full_like(y, 0.1)
array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
>>> y = np.zeros([2, 2, 3], dtype=int)
>>> np.full_like(y, [0, 0, 255])
array([[[ 0, 0, 255],
[ 0, 0, 255]],
[[ 0, 0, 255],
[ 0, 0, 255]]])
numpy.gcd
Python Library Documentation: ufunc
gcd = <ufunc 'gcd'>
gcd(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns the greatest common divisor of ``|x1|`` and ``|x2|``
Parameters
----------
x1, x2 : array_like, int
Arrays of values.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
Returns
-------
y : ndarray or scalar
The greatest common divisor of the absolute value of the inputs
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
lcm : The lowest common multiple
Examples
--------
>>> import numpy as np
>>> np.gcd(12, 20)
4
>>> np.gcd.reduce([15, 25, 35])
5
>>> np.gcd(np.arange(6), 20)
array([20, 1, 2, 1, 4, 5])
numpy.generic
Python Library Documentation: class generic in module numpy class generic(builtins.object) | Base class for numpy scalar types. | | Class from which most (all?) numpy scalar types are derived. For | consistency, exposes the same API as `ndarray`, despite many | consequent attributes being either "get-only," or completely irrelevant. | This is the class from which it is strongly suggested users should derive | custom scalar types. | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
numpy.genfromtxt
Python Library Documentation: function genfromtxt in module numpy
genfromtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=" !#$%&'()*+,-./:;<=>?@[\\]^{|}~", replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding=None, *, ndmin=0, like=None)
Load data from a text file, with missing values handled as specified.
Each line past the first `skip_header` lines is split at the `delimiter`
character, and characters following the `comments` character are discarded.
Parameters
----------
fname : file, str, pathlib.Path, list of str, generator
File, filename, list, or generator to read. If the filename
extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note
that generators must return bytes or strings. The strings
in a list or produced by a generator are treated as lines.
dtype : dtype, optional
Data type of the resulting array.
If None, the dtypes will be determined by the contents of each
column, individually.
comments : str, optional
The character used to indicate the start of a comment.
All the characters occurring on a line after a comment are discarded.
delimiter : str, int, or sequence, optional
The string used to separate values. By default, any consecutive
whitespaces act as delimiter. An integer or sequence of integers
can also be provided as width(s) of each field.
skiprows : int, optional
`skiprows` was removed in numpy 1.10. Please use `skip_header` instead.
skip_header : int, optional
The number of lines to skip at the beginning of the file.
skip_footer : int, optional
The number of lines to skip at the end of the file.
converters : variable, optional
The set of functions that convert the data of a column to a value.
The converters can also be used to provide a default value
for missing data: ``converters = {3: lambda s: float(s or 0)}``.
missing : variable, optional
`missing` was removed in numpy 1.10. Please use `missing_values`
instead.
missing_values : variable, optional
The set of strings corresponding to missing data.
filling_values : variable, optional
The set of values to be used as default when the data are missing.
usecols : sequence, optional
Which columns to read, with 0 being the first. For example,
``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns.
names : {None, True, str, sequence}, optional
If `names` is True, the field names are read from the first line after
the first `skip_header` lines. This line can optionally be preceded
by a comment delimiter. Any content before the comment delimiter is
discarded. If `names` is a sequence or a single-string of
comma-separated names, the names will be used to define the field
names in a structured dtype. If `names` is None, the names of the
dtype fields will be used, if any.
excludelist : sequence, optional
A list of names to exclude. This list is appended to the default list
['return','file','print']. Excluded names are appended with an
underscore: for example, `file` would become `file_`.
deletechars : str, optional
A string combining invalid characters that must be deleted from the
names.
defaultfmt : str, optional
A format used to define default field names, such as "f%i" or "f_%02i".
autostrip : bool, optional
Whether to automatically strip white spaces from the variables.
replace_space : char, optional
Character(s) used in replacement of white spaces in the variable
names. By default, use a '_'.
case_sensitive : {True, False, 'upper', 'lower'}, optional
If True, field names are case sensitive.
If False or 'upper', field names are converted to upper case.
If 'lower', field names are converted to lower case.
unpack : bool, optional
If True, the returned array is transposed, so that arguments may be
unpacked using ``x, y, z = genfromtxt(...)``. When used with a
structured data-type, arrays are returned for each field.
Default is False.
usemask : bool, optional
If True, return a masked array.
If False, return a regular array.
loose : bool, optional
If True, do not raise errors for invalid values.
invalid_raise : bool, optional
If True, an exception is raised if an inconsistency is detected in the
number of columns.
If False, a warning is emitted and the offending lines are skipped.
max_rows : int, optional
The maximum number of rows to read. Must not be used with skip_footer
at the same time. If given, the value must be at least 1. Default is
to read the entire file.
.. versionadded:: 1.10.0
encoding : str, optional
Encoding used to decode the inputfile. Does not apply when `fname`
is a file object. The special value 'bytes' enables backward
compatibility workarounds that ensure that you receive byte arrays
when possible and passes latin1 encoded strings to converters.
Override this value to receive unicode arrays and pass strings
as input to converters. If set to None the system default is used.
The default value is 'bytes'.
.. versionadded:: 1.14.0
.. versionchanged:: 2.0
Before NumPy 2, the default was ``'bytes'`` for Python 2
compatibility. The default is now ``None``.
ndmin : int, optional
Same parameter as `loadtxt`
.. versionadded:: 1.23.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
Data read from the text file. If `usemask` is True, this is a
masked array.
See Also
--------
numpy.loadtxt : equivalent function when no data is missing.
Notes
-----
* When spaces are used as delimiters, or when no delimiter has been given
as input, there should not be any missing data between two fields.
* When variables are named (either by a flexible dtype or with a `names`
sequence), there must not be any header in the file (else a ValueError
exception is raised).
* Individual values are not stripped of spaces by default.
When using a custom converter, make sure the function does remove spaces.
* Custom converters may receive unexpected values due to dtype
discovery.
References
----------
.. [1] NumPy User Guide, section `I/O with NumPy
<https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html>`_.
Examples
--------
>>> from io import StringIO
>>> import numpy as np
Comma delimited file with mixed dtype
>>> s = StringIO("1,1.3,abcde")
>>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'),
... ('mystring','S5')], delimiter=",")
>>> data
array((1, 1.3, b'abcde'),
dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])
Using dtype = None
>>> _ = s.seek(0) # needed for StringIO example only
>>> data = np.genfromtxt(s, dtype=None,
... names = ['myint','myfloat','mystring'], delimiter=",")
>>> data
array((1, 1.3, 'abcde'),
dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '<U5')])
Specifying dtype and names
>>> _ = s.seek(0)
>>> data = np.genfromtxt(s, dtype="i8,f8,S5",
... names=['myint','myfloat','mystring'], delimiter=",")
>>> data
array((1, 1.3, b'abcde'),
dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])
An example with fixed-width columns
>>> s = StringIO("11.3abcde")
>>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],
... delimiter=[1,3,5])
>>> data
array((1, 1.3, 'abcde'),
dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', '<U5')])
An example to show comments
>>> f = StringIO('''
... text,# of chars
... hello world,11
... numpy,5''')
>>> np.genfromtxt(f, dtype='S12,S12', delimiter=',')
array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')],
dtype=[('f0', 'S12'), ('f1', 'S12')])
numpy.geomspace
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0)
Return numbers spaced evenly on a log scale (a geometric progression).
This is similar to `logspace`, but with endpoints specified directly.
Each output sample is a constant multiple of the previous.
.. versionchanged:: 1.16.0
Non-scalar `start` and `stop` are now supported.
Parameters
----------
start : array_like
The starting value of the sequence.
stop : array_like
The final value of the sequence, unless `endpoint` is False.
In that case, ``num + 1`` values are spaced over the
interval in log-space, of which all but the last (a sequence of
length `num`) are returned.
num : integer, optional
Number of samples to generate. Default is 50.
endpoint : boolean, optional
If true, `stop` is the last sample. Otherwise, it is not included.
Default is True.
dtype : dtype
The type of the output array. If `dtype` is not given, the data type
is inferred from `start` and `stop`. The inferred dtype will never be
an integer; `float` is chosen even if the arguments would produce an
array of integers.
axis : int, optional
The axis in the result to store the samples. Relevant only if start
or stop are array-like. By default (0), the samples will be along a
new axis inserted at the beginning. Use -1 to get an axis at the end.
.. versionadded:: 1.16.0
Returns
-------
samples : ndarray
`num` samples, equally spaced on a log scale.
See Also
--------
logspace : Similar to geomspace, but with endpoints specified using log
and base.
linspace : Similar to geomspace, but with arithmetic instead of geometric
progression.
arange : Similar to linspace, with the step size specified instead of the
number of samples.
:ref:`how-to-partition`
Notes
-----
If the inputs or dtype are complex, the output will follow a logarithmic
spiral in the complex plane. (There are an infinite number of spirals
passing through two points; the output will follow the shortest such path.)
Examples
--------
>>> import numpy as np
>>> np.geomspace(1, 1000, num=4)
array([ 1., 10., 100., 1000.])
>>> np.geomspace(1, 1000, num=3, endpoint=False)
array([ 1., 10., 100.])
>>> np.geomspace(1, 1000, num=4, endpoint=False)
array([ 1. , 5.62341325, 31.6227766 , 177.827941 ])
>>> np.geomspace(1, 256, num=9)
array([ 1., 2., 4., 8., 16., 32., 64., 128., 256.])
Note that the above may not produce exact integers:
>>> np.geomspace(1, 256, num=9, dtype=int)
array([ 1, 2, 4, 7, 16, 32, 63, 127, 256])
>>> np.around(np.geomspace(1, 256, num=9)).astype(int)
array([ 1, 2, 4, 8, 16, 32, 64, 128, 256])
Negative, decreasing, and complex inputs are allowed:
>>> np.geomspace(1000, 1, num=4)
array([1000., 100., 10., 1.])
>>> np.geomspace(-1000, -1, num=4)
array([-1000., -100., -10., -1.])
>>> np.geomspace(1j, 1000j, num=4) # Straight line
array([0. +1.j, 0. +10.j, 0. +100.j, 0.+1000.j])
>>> np.geomspace(-1+0j, 1+0j, num=5) # Circle
array([-1.00000000e+00+1.22464680e-16j, -7.07106781e-01+7.07106781e-01j,
6.12323400e-17+1.00000000e+00j, 7.07106781e-01+7.07106781e-01j,
1.00000000e+00+0.00000000e+00j])
Graphical illustration of `endpoint` parameter:
>>> import matplotlib.pyplot as plt
>>> N = 10
>>> y = np.zeros(N)
>>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=True), y + 1, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.semilogx(np.geomspace(1, 1000, N, endpoint=False), y + 2, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.axis([0.5, 2000, 0, 3])
[0.5, 2000, 0, 3]
>>> plt.grid(True, color='0.7', linestyle='-', which='both', axis='both')
>>> plt.show()
numpy.get_include
Python Library Documentation: function get_include in module numpy
get_include()
Return the directory that contains the NumPy \*.h header files.
Extension modules that need to compile against NumPy may need to use this
function to locate the appropriate include directory.
Notes
-----
When using ``setuptools``, for example in ``setup.py``::
import numpy as np
...
Extension('extension_name', ...
include_dirs=[np.get_include()])
...
Note that a CLI tool ``numpy-config`` was introduced in NumPy 2.0, using
that is likely preferred for build systems other than ``setuptools``::
$ numpy-config --cflags
-I/path/to/site-packages/numpy/_core/include
# Or rely on pkg-config:
$ export PKG_CONFIG_PATH=$(numpy-config --pkgconfigdir)
$ pkg-config --cflags
-I/path/to/site-packages/numpy/_core/include
Examples
--------
>>> np.get_include()
'.../site-packages/numpy/core/include' # may vary
numpy.get_printoptions
Python Library Documentation: function get_printoptions in module numpy
get_printoptions()
Return the current print options.
Returns
-------
print_opts : dict
Dictionary of current print options with keys
- precision : int
- threshold : int
- edgeitems : int
- linewidth : int
- suppress : bool
- nanstr : str
- infstr : str
- sign : str
- formatter : dict of callables
- floatmode : str
- legacy : str or False
For a full description of these options, see `set_printoptions`.
See Also
--------
set_printoptions, printoptions
Examples
--------
>>> import numpy as np
>>> np.get_printoptions()
{'edgeitems': 3, 'threshold': 1000, ..., 'override_repr': None}
>>> np.get_printoptions()['linewidth']
75
>>> np.set_printoptions(linewidth=100)
>>> np.get_printoptions()['linewidth']
100
numpy.getbufsize
Python Library Documentation: function getbufsize in module numpy
getbufsize()
Return the size of the buffer used in ufuncs.
Returns
-------
getbufsize : int
Size of ufunc buffer in bytes.
Examples
--------
>>> import numpy as np
>>> np.getbufsize()
8192
numpy.geterr
Python Library Documentation: function geterr in module numpy
geterr()
Get the current way of handling floating-point errors.
Returns
-------
res : dict
A dictionary with keys "divide", "over", "under", and "invalid",
whose values are from the strings "ignore", "print", "log", "warn",
"raise", and "call". The keys represent possible floating-point
exceptions, and the values define how these exceptions are handled.
See Also
--------
geterrcall, seterr, seterrcall
Notes
-----
For complete documentation of the types of floating-point exceptions and
treatment options, see `seterr`.
Examples
--------
>>> import numpy as np
>>> np.geterr()
{'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
>>> np.arange(3.) / np.arange(3.) # doctest: +SKIP
array([nan, 1., 1.])
RuntimeWarning: invalid value encountered in divide
>>> oldsettings = np.seterr(all='warn', invalid='raise')
>>> np.geterr()
{'divide': 'warn', 'over': 'warn', 'under': 'warn', 'invalid': 'raise'}
>>> np.arange(3.) / np.arange(3.)
Traceback (most recent call last):
...
FloatingPointError: invalid value encountered in divide
>>> oldsettings = np.seterr(**oldsettings) # restore original
numpy.geterrcall
Python Library Documentation: function geterrcall in module numpy
geterrcall()
Return the current callback function used on floating-point errors.
When the error handling for a floating-point error (one of "divide",
"over", "under", or "invalid") is set to 'call' or 'log', the function
that is called or the log instance that is written to is returned by
`geterrcall`. This function or log instance has been set with
`seterrcall`.
Returns
-------
errobj : callable, log instance or None
The current error handler. If no handler was set through `seterrcall`,
``None`` is returned.
See Also
--------
seterrcall, seterr, geterr
Notes
-----
For complete documentation of the types of floating-point exceptions and
treatment options, see `seterr`.
Examples
--------
>>> import numpy as np
>>> np.geterrcall() # we did not yet set a handler, returns None
>>> orig_settings = np.seterr(all='call')
>>> def err_handler(type, flag):
... print("Floating point error (%s), with flag %s" % (type, flag))
>>> old_handler = np.seterrcall(err_handler)
>>> np.array([1, 2, 3]) / 0.0
Floating point error (divide by zero), with flag 1
array([inf, inf, inf])
>>> cur_handler = np.geterrcall()
>>> cur_handler is err_handler
True
>>> old_settings = np.seterr(**orig_settings) # restore original
>>> old_handler = np.seterrcall(None) # restore original
numpy.gradient
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
gradient(f, *varargs, axis=None, edge_order=1)
Return the gradient of an N-dimensional array.
The gradient is computed using second order accurate central differences
in the interior points and either first or second order accurate one-sides
(forward or backwards) differences at the boundaries.
The returned gradient hence has the same shape as the input array.
Parameters
----------
f : array_like
An N-dimensional array containing samples of a scalar function.
varargs : list of scalar or array, optional
Spacing between f values. Default unitary spacing for all dimensions.
Spacing can be specified using:
1. single scalar to specify a sample distance for all dimensions.
2. N scalars to specify a constant sample distance for each dimension.
i.e. `dx`, `dy`, `dz`, ...
3. N arrays to specify the coordinates of the values along each
dimension of F. The length of the array must match the size of
the corresponding dimension
4. Any combination of N scalars/arrays with the meaning of 2. and 3.
If `axis` is given, the number of varargs must equal the number of axes.
Default: 1. (see Examples below).
edge_order : {1, 2}, optional
Gradient is calculated using N-th order accurate differences
at the boundaries. Default: 1.
.. versionadded:: 1.9.1
axis : None or int or tuple of ints, optional
Gradient is calculated only along the given axis or axes
The default (axis = None) is to calculate the gradient for all the axes
of the input array. axis may be negative, in which case it counts from
the last to the first axis.
.. versionadded:: 1.11.0
Returns
-------
gradient : ndarray or tuple of ndarray
A tuple of ndarrays (or a single ndarray if there is only one
dimension) corresponding to the derivatives of f with respect
to each dimension. Each derivative has the same shape as f.
Examples
--------
>>> import numpy as np
>>> f = np.array([1, 2, 4, 7, 11, 16])
>>> np.gradient(f)
array([1. , 1.5, 2.5, 3.5, 4.5, 5. ])
>>> np.gradient(f, 2)
array([0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ])
Spacing can be also specified with an array that represents the coordinates
of the values F along the dimensions.
For instance a uniform spacing:
>>> x = np.arange(f.size)
>>> np.gradient(f, x)
array([1. , 1.5, 2.5, 3.5, 4.5, 5. ])
Or a non uniform one:
>>> x = np.array([0., 1., 1.5, 3.5, 4., 6.])
>>> np.gradient(f, x)
array([1. , 3. , 3.5, 6.7, 6.9, 2.5])
For two dimensional arrays, the return will be two arrays ordered by
axis. In this example the first array stands for the gradient in
rows and the second one in columns direction:
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]]))
(array([[ 2., 2., -1.],
[ 2., 2., -1.]]),
array([[1. , 2.5, 4. ],
[1. , 1. , 1. ]]))
In this example the spacing is also specified:
uniform for axis=0 and non uniform for axis=1
>>> dx = 2.
>>> y = [1., 1.5, 3.5]
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]]), dx, y)
(array([[ 1. , 1. , -0.5],
[ 1. , 1. , -0.5]]),
array([[2. , 2. , 2. ],
[2. , 1.7, 0.5]]))
It is possible to specify how boundaries are treated using `edge_order`
>>> x = np.array([0, 1, 2, 3, 4])
>>> f = x**2
>>> np.gradient(f, edge_order=1)
array([1., 2., 4., 6., 7.])
>>> np.gradient(f, edge_order=2)
array([0., 2., 4., 6., 8.])
The `axis` keyword can be used to specify a subset of axes of which the
gradient is calculated
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]]), axis=0)
array([[ 2., 2., -1.],
[ 2., 2., -1.]])
The `varargs` argument defines the spacing between sample points in the
input array. It can take two forms:
1. An array, specifying coordinates, which may be unevenly spaced:
>>> x = np.array([0., 2., 3., 6., 8.])
>>> y = x ** 2
>>> np.gradient(y, x, edge_order=2)
array([ 0., 4., 6., 12., 16.])
2. A scalar, representing the fixed sample distance:
>>> dx = 2
>>> x = np.array([0., 2., 4., 6., 8.])
>>> y = x ** 2
>>> np.gradient(y, dx, edge_order=2)
array([ 0., 4., 8., 12., 16.])
It's possible to provide different data for spacing along each dimension.
The number of arguments must match the number of dimensions in the input
data.
>>> dx = 2
>>> dy = 3
>>> x = np.arange(0, 6, dx)
>>> y = np.arange(0, 9, dy)
>>> xs, ys = np.meshgrid(x, y)
>>> zs = xs + 2 * ys
>>> np.gradient(zs, dy, dx) # Passing two scalars
(array([[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.]]),
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]))
Mixing scalars and arrays is also allowed:
>>> np.gradient(zs, y, dx) # Passing one array and one scalar
(array([[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.]]),
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]))
Notes
-----
Assuming that :math:`f\in C^{3}` (i.e., :math:`f` has at least 3 continuous
derivatives) and let :math:`h_{*}` be a non-homogeneous stepsize, we
minimize the "consistency error" :math:`\eta_{i}` between the true gradient
and its estimate from a linear combination of the neighboring grid-points:
.. math::
\eta_{i} = f_{i}^{\left(1\right)} -
\left[ \alpha f\left(x_{i}\right) +
\beta f\left(x_{i} + h_{d}\right) +
\gamma f\left(x_{i}-h_{s}\right)
\right]
By substituting :math:`f(x_{i} + h_{d})` and :math:`f(x_{i} - h_{s})`
with their Taylor series expansion, this translates into solving
the following the linear system:
.. math::
\left\{
\begin{array}{r}
\alpha+\beta+\gamma=0 \\
\beta h_{d}-\gamma h_{s}=1 \\
\beta h_{d}^{2}+\gamma h_{s}^{2}=0
\end{array}
\right.
The resulting approximation of :math:`f_{i}^{(1)}` is the following:
.. math::
\hat f_{i}^{(1)} =
\frac{
h_{s}^{2}f\left(x_{i} + h_{d}\right)
+ \left(h_{d}^{2} - h_{s}^{2}\right)f\left(x_{i}\right)
- h_{d}^{2}f\left(x_{i}-h_{s}\right)}
{ h_{s}h_{d}\left(h_{d} + h_{s}\right)}
+ \mathcal{O}\left(\frac{h_{d}h_{s}^{2}
+ h_{s}h_{d}^{2}}{h_{d}
+ h_{s}}\right)
It is worth noting that if :math:`h_{s}=h_{d}`
(i.e., data are evenly spaced)
we find the standard second order approximation:
.. math::
\hat f_{i}^{(1)}=
\frac{f\left(x_{i+1}\right) - f\left(x_{i-1}\right)}{2h}
+ \mathcal{O}\left(h^{2}\right)
With a similar procedure the forward/backward approximations used for
boundaries can be derived.
References
----------
.. [1] Quarteroni A., Sacco R., Saleri F. (2007) Numerical Mathematics
(Texts in Applied Mathematics). New York: Springer.
.. [2] Durran D. R. (1999) Numerical Methods for Wave Equations
in Geophysical Fluid Dynamics. New York: Springer.
.. [3] Fornberg B. (1988) Generation of Finite Difference Formulas on
Arbitrarily Spaced Grids,
Mathematics of Computation 51, no. 184 : 699-706.
`PDF <https://www.ams.org/journals/mcom/1988-51-184/
S0025-5718-1988-0935077-0/S0025-5718-1988-0935077-0.pdf>`_.
numpy.greater
Python Library Documentation: ufunc
greater = <ufunc 'greater'>
greater(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 > x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
greater_equal, less, less_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.greater([4,2],[2,2])
array([ True, False])
The ``>`` operator can be used as a shorthand for ``np.greater`` on
ndarrays.
>>> a = np.array([4, 2])
>>> b = np.array([2, 2])
>>> a > b
array([ True, False])
numpy.greater_equal
Python Library Documentation: ufunc
greater_equal = <ufunc 'greater_equal'>
greater_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 >= x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : bool or ndarray of bool
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
--------
greater, less, less_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.greater_equal([4, 2, 1], [2, 2, 2])
array([ True, True, False])
The ``>=`` operator can be used as a shorthand for ``np.greater_equal``
on ndarrays.
>>> a = np.array([4, 2, 1])
>>> b = np.array([2, 2, 2])
>>> a >= b
array([ True, True, False])
numpy.half
Python Library Documentation: class float16 in module numpy class float16(floating) | Half-precision floating-point number type. | | :Character code: ``'e'`` | :Canonical name: `numpy.half` | :Alias on this platform (win32 AMD64): `numpy.float16`: 16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa. | | Method resolution order: | float16 | floating | inexact | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | as_integer_ratio(...) | half.as_integer_ratio() -> (int, int) | | Return a pair of integers, whose ratio is exactly equal to the original | floating point number, and with a positive denominator. | Raise `OverflowError` on infinities and a `ValueError` on NaNs. | | >>> np.half(10.0).as_integer_ratio() | (10, 1) | >>> np.half(0.0).as_integer_ratio() | (0, 1) | >>> np.half(-.25).as_integer_ratio() | (-1, 4) | | is_integer(...) | half.is_integer() -> bool | | Return ``True`` if the floating point number is finite with integral | value, and ``False`` otherwise. | | .. versionadded:: 1.22 | | Examples | -------- | >>> np.half(-2.0).is_integer() | True | >>> np.half(3.2).is_integer() | False | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from floating: | | __round__(...) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __reduce__(...) | Helper for pickle. | | __rlshift__(self, value, /) | Return value<<self. | | __ror__(self, value, /) | Return value|self. | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.hamming
Python Library Documentation: function hamming in module numpy
hamming(M)
Return the Hamming window.
The Hamming window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : ndarray
The window, with the maximum value normalized to one (the value
one appears only if the number of samples is odd).
See Also
--------
bartlett, blackman, hanning, kaiser
Notes
-----
The Hamming window is defined as
.. math:: w(n) = 0.54 - 0.46\cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hamming was named for R. W. Hamming, an associate of J. W. Tukey
and is described in Blackman and Tukey. It was recommended for
smoothing the truncated autocovariance function in the time domain.
Most references to the Hamming window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 109-110.
.. [3] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> import numpy as np
>>> np.hamming(12)
array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594, # may vary
0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909,
0.15302337, 0.08 ])
Plot the window and the frequency response.
.. plot::
:include-source:
import matplotlib.pyplot as plt
from numpy.fft import fft, fftshift
window = np.hamming(51)
plt.plot(window)
plt.title("Hamming window")
plt.ylabel("Amplitude")
plt.xlabel("Sample")
plt.show()
plt.figure()
A = fft(window, 2048) / 25.5
mag = np.abs(fftshift(A))
freq = np.linspace(-0.5, 0.5, len(A))
response = 20 * np.log10(mag)
response = np.clip(response, -100, 100)
plt.plot(freq, response)
plt.title("Frequency response of Hamming window")
plt.ylabel("Magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
plt.axis('tight')
plt.show()
numpy.hanning
Python Library Documentation: function hanning in module numpy
hanning(M)
Return the Hanning window.
The Hanning window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : ndarray, shape(M,)
The window, with the maximum value normalized to one (the value
one appears only if `M` is odd).
See Also
--------
bartlett, blackman, hamming, kaiser
Notes
-----
The Hanning window is defined as
.. math:: w(n) = 0.5 - 0.5\cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hanning was named for Julius von Hann, an Austrian meteorologist.
It is also known as the Cosine Bell. Some authors prefer that it be
called a Hann window, to help avoid confusion with the very similar
Hamming window.
Most references to the Hanning window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 106-108.
.. [3] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> import numpy as np
>>> np.hanning(12)
array([0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037,
0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249,
0.07937323, 0. ])
Plot the window and its frequency response.
.. plot::
:include-source:
import matplotlib.pyplot as plt
from numpy.fft import fft, fftshift
window = np.hanning(51)
plt.plot(window)
plt.title("Hann window")
plt.ylabel("Amplitude")
plt.xlabel("Sample")
plt.show()
plt.figure()
A = fft(window, 2048) / 25.5
mag = np.abs(fftshift(A))
freq = np.linspace(-0.5, 0.5, len(A))
with np.errstate(divide='ignore', invalid='ignore'):
response = 20 * np.log10(mag)
response = np.clip(response, -100, 100)
plt.plot(freq, response)
plt.title("Frequency response of the Hann window")
plt.ylabel("Magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
plt.axis('tight')
plt.show()
numpy.heaviside
Python Library Documentation: ufunc
heaviside = <ufunc 'heaviside'>
heaviside(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the Heaviside step function.
The Heaviside step function [1]_ is defined as::
0 if x1 < 0
heaviside(x1, x2) = x2 if x1 == 0
1 if x1 > 0
where `x2` is often taken to be 0.5, but 0 and 1 are also sometimes used.
Parameters
----------
x1 : array_like
Input values.
x2 : array_like
The value of the function when x1 is 0.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
The output array, element-wise Heaviside step function of `x1`.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
.. versionadded:: 1.13.0
References
----------
.. [1] Wikipedia, "Heaviside step function",
https://en.wikipedia.org/wiki/Heaviside_step_function
Examples
--------
>>> import numpy as np
>>> np.heaviside([-1.5, 0, 2.0], 0.5)
array([ 0. , 0.5, 1. ])
>>> np.heaviside([-1.5, 0, 2.0], 1)
array([ 0., 1., 1.])
numpy.histogram
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
histogram(a, bins=10, range=None, density=None, weights=None)
Compute the histogram of a dataset.
Parameters
----------
a : array_like
Input data. The histogram is computed over the flattened array.
bins : int or sequence of scalars or str, optional
If `bins` is an int, it defines the number of equal-width
bins in the given range (10, by default). If `bins` is a
sequence, it defines a monotonically increasing array of bin edges,
including the rightmost edge, allowing for non-uniform bin widths.
.. versionadded:: 1.11.0
If `bins` is a string, it defines the method used to calculate the
optimal bin width, as defined by `histogram_bin_edges`.
range : (float, float), optional
The lower and upper range of the bins. If not provided, range
is simply ``(a.min(), a.max())``. Values outside the range are
ignored. The first element of the range must be less than or
equal to the second. `range` affects the automatic bin
computation as well. While bin width is computed to be optimal
based on the actual data within `range`, the bin count will fill
the entire range including portions containing no data.
weights : array_like, optional
An array of weights, of the same shape as `a`. Each value in
`a` only contributes its associated weight towards the bin count
(instead of 1). If `density` is True, the weights are
normalized, so that the integral of the density over the range
remains 1.
Please note that the ``dtype`` of `weights` will also become the
``dtype`` of the returned accumulator (`hist`), so it must be
large enough to hold accumulated values as well.
density : bool, optional
If ``False``, the result will contain the number of samples in
each bin. If ``True``, the result is the value of the
probability *density* function at the bin, normalized such that
the *integral* over the range is 1. Note that the sum of the
histogram values will not be equal to 1 unless bins of unity
width are chosen; it is not a probability *mass* function.
Returns
-------
hist : array
The values of the histogram. See `density` and `weights` for a
description of the possible semantics. If `weights` are given,
``hist.dtype`` will be taken from `weights`.
bin_edges : array of dtype float
Return the bin edges ``(length(hist)+1)``.
See Also
--------
histogramdd, bincount, searchsorted, digitize, histogram_bin_edges
Notes
-----
All but the last (righthand-most) bin is half-open. In other words,
if `bins` is::
[1, 2, 3, 4]
then the first bin is ``[1, 2)`` (including 1, but excluding 2) and
the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which
*includes* 4.
Examples
--------
>>> import numpy as np
>>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]))
>>> np.histogram(np.arange(4), bins=np.arange(5), density=True)
(array([0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4]))
>>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3])
(array([1, 4, 1]), array([0, 1, 2, 3]))
>>> a = np.arange(5)
>>> hist, bin_edges = np.histogram(a, density=True)
>>> hist
array([0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5])
>>> hist.sum()
2.4999999999999996
>>> np.sum(hist * np.diff(bin_edges))
1.0
.. versionadded:: 1.11.0
Automated Bin Selection Methods example, using 2 peak random data
with 2000 points.
.. plot::
:include-source:
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.RandomState(10) # deterministic random data
a = np.hstack((rng.normal(size=1000),
rng.normal(loc=5, scale=2, size=1000)))
plt.hist(a, bins='auto') # arguments are passed to np.histogram
plt.title("Histogram with 'auto' bins")
plt.show()
numpy.histogram2d
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
histogram2d(x, y, bins=10, range=None, density=None, weights=None)
Compute the bi-dimensional histogram of two data samples.
Parameters
----------
x : array_like, shape (N,)
An array containing the x coordinates of the points to be
histogrammed.
y : array_like, shape (N,)
An array containing the y coordinates of the points to be
histogrammed.
bins : int or array_like or [int, int] or [array, array], optional
The bin specification:
* If int, the number of bins for the two dimensions (nx=ny=bins).
* If array_like, the bin edges for the two dimensions
(x_edges=y_edges=bins).
* If [int, int], the number of bins in each dimension
(nx, ny = bins).
* If [array, array], the bin edges in each dimension
(x_edges, y_edges = bins).
* A combination [int, array] or [array, int], where int
is the number of bins and array is the bin edges.
range : array_like, shape(2,2), optional
The leftmost and rightmost edges of the bins along each dimension
(if not specified explicitly in the `bins` parameters):
``[[xmin, xmax], [ymin, ymax]]``. All values outside of this range
will be considered outliers and not tallied in the histogram.
density : bool, optional
If False, the default, returns the number of samples in each bin.
If True, returns the probability *density* function at the bin,
``bin_count / sample_count / bin_area``.
weights : array_like, shape(N,), optional
An array of values ``w_i`` weighing each sample ``(x_i, y_i)``.
Weights are normalized to 1 if `density` is True. If `density` is
False, the values of the returned histogram are equal to the sum of
the weights belonging to the samples falling into each bin.
Returns
-------
H : ndarray, shape(nx, ny)
The bi-dimensional histogram of samples `x` and `y`. Values in `x`
are histogrammed along the first dimension and values in `y` are
histogrammed along the second dimension.
xedges : ndarray, shape(nx+1,)
The bin edges along the first dimension.
yedges : ndarray, shape(ny+1,)
The bin edges along the second dimension.
See Also
--------
histogram : 1D histogram
histogramdd : Multidimensional histogram
Notes
-----
When `density` is True, then the returned histogram is the sample
density, defined such that the sum over bins of the product
``bin_value * bin_area`` is 1.
Please note that the histogram does not follow the Cartesian convention
where `x` values are on the abscissa and `y` values on the ordinate
axis. Rather, `x` is histogrammed along the first dimension of the
array (vertical), and `y` along the second dimension of the array
(horizontal). This ensures compatibility with `histogramdd`.
Examples
--------
>>> import numpy as np
>>> from matplotlib.image import NonUniformImage
>>> import matplotlib.pyplot as plt
Construct a 2-D histogram with variable bin width. First define the bin
edges:
>>> xedges = [0, 1, 3, 5]
>>> yedges = [0, 2, 3, 4, 6]
Next we create a histogram H with random bin content:
>>> x = np.random.normal(2, 1, 100)
>>> y = np.random.normal(1, 1, 100)
>>> H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges))
>>> # Histogram does not follow Cartesian convention (see Notes),
>>> # therefore transpose H for visualization purposes.
>>> H = H.T
:func:`imshow <matplotlib.pyplot.imshow>` can only display square bins:
>>> fig = plt.figure(figsize=(7, 3))
>>> ax = fig.add_subplot(131, title='imshow: square bins')
>>> plt.imshow(H, interpolation='nearest', origin='lower',
... extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
<matplotlib.image.AxesImage object at 0x...>
:func:`pcolormesh <matplotlib.pyplot.pcolormesh>` can display actual edges:
>>> ax = fig.add_subplot(132, title='pcolormesh: actual edges',
... aspect='equal')
>>> X, Y = np.meshgrid(xedges, yedges)
>>> ax.pcolormesh(X, Y, H)
<matplotlib.collections.QuadMesh object at 0x...>
:class:`NonUniformImage <matplotlib.image.NonUniformImage>` can be used to
display actual bin edges with interpolation:
>>> ax = fig.add_subplot(133, title='NonUniformImage: interpolated',
... aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]])
>>> im = NonUniformImage(ax, interpolation='bilinear')
>>> xcenters = (xedges[:-1] + xedges[1:]) / 2
>>> ycenters = (yedges[:-1] + yedges[1:]) / 2
>>> im.set_data(xcenters, ycenters, H)
>>> ax.add_image(im)
>>> plt.show()
It is also possible to construct a 2-D histogram without specifying bin
edges:
>>> # Generate non-symmetric test data
>>> n = 10000
>>> x = np.linspace(1, 100, n)
>>> y = 2*np.log(x) + np.random.rand(n) - 0.5
>>> # Compute 2d histogram. Note the order of x/y and xedges/yedges
>>> H, yedges, xedges = np.histogram2d(y, x, bins=20)
Now we can plot the histogram using
:func:`pcolormesh <matplotlib.pyplot.pcolormesh>`, and a
:func:`hexbin <matplotlib.pyplot.hexbin>` for comparison.
>>> # Plot histogram using pcolormesh
>>> fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)
>>> ax1.pcolormesh(xedges, yedges, H, cmap='rainbow')
>>> ax1.plot(x, 2*np.log(x), 'k-')
>>> ax1.set_xlim(x.min(), x.max())
>>> ax1.set_ylim(y.min(), y.max())
>>> ax1.set_xlabel('x')
>>> ax1.set_ylabel('y')
>>> ax1.set_title('histogram2d')
>>> ax1.grid()
>>> # Create hexbin plot for comparison
>>> ax2.hexbin(x, y, gridsize=20, cmap='rainbow')
>>> ax2.plot(x, 2*np.log(x), 'k-')
>>> ax2.set_title('hexbin')
>>> ax2.set_xlim(x.min(), x.max())
>>> ax2.set_xlabel('x')
>>> ax2.grid()
>>> plt.show()
numpy.histogram_bin_edges
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
histogram_bin_edges(a, bins=10, range=None, weights=None)
Function to calculate only the edges of the bins used by the `histogram`
function.
Parameters
----------
a : array_like
Input data. The histogram is computed over the flattened array.
bins : int or sequence of scalars or str, optional
If `bins` is an int, it defines the number of equal-width
bins in the given range (10, by default). If `bins` is a
sequence, it defines the bin edges, including the rightmost
edge, allowing for non-uniform bin widths.
If `bins` is a string from the list below, `histogram_bin_edges` will
use the method chosen to calculate the optimal bin width and
consequently the number of bins (see the Notes section for more detail
on the estimators) from the data that falls within the requested range.
While the bin width will be optimal for the actual data
in the range, the number of bins will be computed to fill the
entire range, including the empty portions. For visualisation,
using the 'auto' option is suggested. Weighted data is not
supported for automated bin size selection.
'auto'
Minimum bin width between the 'sturges' and 'fd' estimators.
Provides good all-around performance.
'fd' (Freedman Diaconis Estimator)
Robust (resilient to outliers) estimator that takes into
account data variability and data size.
'doane'
An improved version of Sturges' estimator that works better
with non-normal datasets.
'scott'
Less robust estimator that takes into account data variability
and data size.
'stone'
Estimator based on leave-one-out cross-validation estimate of
the integrated squared error. Can be regarded as a generalization
of Scott's rule.
'rice'
Estimator does not take variability into account, only data
size. Commonly overestimates number of bins required.
'sturges'
R's default method, only accounts for data size. Only
optimal for gaussian data and underestimates number of bins
for large non-gaussian datasets.
'sqrt'
Square root (of data size) estimator, used by Excel and
other programs for its speed and simplicity.
range : (float, float), optional
The lower and upper range of the bins. If not provided, range
is simply ``(a.min(), a.max())``. Values outside the range are
ignored. The first element of the range must be less than or
equal to the second. `range` affects the automatic bin
computation as well. While bin width is computed to be optimal
based on the actual data within `range`, the bin count will fill
the entire range including portions containing no data.
weights : array_like, optional
An array of weights, of the same shape as `a`. Each value in
`a` only contributes its associated weight towards the bin count
(instead of 1). This is currently not used by any of the bin estimators,
but may be in the future.
Returns
-------
bin_edges : array of dtype float
The edges to pass into `histogram`
See Also
--------
histogram
Notes
-----
The methods to estimate the optimal number of bins are well founded
in literature, and are inspired by the choices R provides for
histogram visualisation. Note that having the number of bins
proportional to :math:`n^{1/3}` is asymptotically optimal, which is
why it appears in most estimators. These are simply plug-in methods
that give good starting points for number of bins. In the equations
below, :math:`h` is the binwidth and :math:`n_h` is the number of
bins. All estimators that compute bin counts are recast to bin width
using the `ptp` of the data. The final bin count is obtained from
``np.round(np.ceil(range / h))``. The final bin width is often less
than what is returned by the estimators below.
'auto' (minimum bin width of the 'sturges' and 'fd' estimators)
A compromise to get a good value. For small datasets the Sturges
value will usually be chosen, while larger datasets will usually
default to FD. Avoids the overly conservative behaviour of FD
and Sturges for small and large datasets respectively.
Switchover point is usually :math:`a.size \approx 1000`.
'fd' (Freedman Diaconis Estimator)
.. math:: h = 2 \frac{IQR}{n^{1/3}}
The binwidth is proportional to the interquartile range (IQR)
and inversely proportional to cube root of a.size. Can be too
conservative for small datasets, but is quite good for large
datasets. The IQR is very robust to outliers.
'scott'
.. math:: h = \sigma \sqrt[3]{\frac{24 \sqrt{\pi}}{n}}
The binwidth is proportional to the standard deviation of the
data and inversely proportional to cube root of ``x.size``. Can
be too conservative for small datasets, but is quite good for
large datasets. The standard deviation is not very robust to
outliers. Values are very similar to the Freedman-Diaconis
estimator in the absence of outliers.
'rice'
.. math:: n_h = 2n^{1/3}
The number of bins is only proportional to cube root of
``a.size``. It tends to overestimate the number of bins and it
does not take into account data variability.
'sturges'
.. math:: n_h = \log _{2}(n) + 1
The number of bins is the base 2 log of ``a.size``. This
estimator assumes normality of data and is too conservative for
larger, non-normal datasets. This is the default method in R's
``hist`` method.
'doane'
.. math:: n_h = 1 + \log_{2}(n) +
\log_{2}\left(1 + \frac{|g_1|}{\sigma_{g_1}}\right)
g_1 = mean\left[\left(\frac{x - \mu}{\sigma}\right)^3\right]
\sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}}
An improved version of Sturges' formula that produces better
estimates for non-normal datasets. This estimator attempts to
account for the skew of the data.
'sqrt'
.. math:: n_h = \sqrt n
The simplest and fastest estimator. Only takes into account the
data size.
Additionally, if the data is of integer dtype, then the binwidth will never
be less than 1.
Examples
--------
>>> import numpy as np
>>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5])
>>> np.histogram_bin_edges(arr, bins='auto', range=(0, 1))
array([0. , 0.25, 0.5 , 0.75, 1. ])
>>> np.histogram_bin_edges(arr, bins=2)
array([0. , 2.5, 5. ])
For consistency with histogram, an array of pre-computed bins is
passed through unmodified:
>>> np.histogram_bin_edges(arr, [1, 2])
array([1, 2])
This function allows one set of bins to be computed, and reused across
multiple histograms:
>>> shared_bins = np.histogram_bin_edges(arr, bins='auto')
>>> shared_bins
array([0., 1., 2., 3., 4., 5.])
>>> group_id = np.array([0, 1, 1, 0, 1, 1, 0, 1, 1])
>>> hist_0, _ = np.histogram(arr[group_id == 0], bins=shared_bins)
>>> hist_1, _ = np.histogram(arr[group_id == 1], bins=shared_bins)
>>> hist_0; hist_1
array([1, 1, 0, 1, 0])
array([2, 0, 1, 1, 2])
Which gives more easily comparable results than using separate bins for
each histogram:
>>> hist_0, bins_0 = np.histogram(arr[group_id == 0], bins='auto')
>>> hist_1, bins_1 = np.histogram(arr[group_id == 1], bins='auto')
>>> hist_0; hist_1
array([1, 1, 1])
array([2, 1, 1, 2])
>>> bins_0; bins_1
array([0., 1., 2., 3.])
array([0. , 1.25, 2.5 , 3.75, 5. ])
numpy.histogramdd
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
histogramdd(sample, bins=10, range=None, density=None, weights=None)
Compute the multidimensional histogram of some data.
Parameters
----------
sample : (N, D) array, or (N, D) array_like
The data to be histogrammed.
Note the unusual interpretation of sample when an array_like:
* When an array, each row is a coordinate in a D-dimensional space -
such as ``histogramdd(np.array([p1, p2, p3]))``.
* When an array_like, each element is the list of values for single
coordinate - such as ``histogramdd((X, Y, Z))``.
The first form should be preferred.
bins : sequence or int, optional
The bin specification:
* A sequence of arrays describing the monotonically increasing bin
edges along each dimension.
* The number of bins for each dimension (nx, ny, ... =bins)
* The number of bins for all dimensions (nx=ny=...=bins).
range : sequence, optional
A sequence of length D, each an optional (lower, upper) tuple giving
the outer bin edges to be used if the edges are not given explicitly in
`bins`.
An entry of None in the sequence results in the minimum and maximum
values being used for the corresponding dimension.
The default, None, is equivalent to passing a tuple of D None values.
density : bool, optional
If False, the default, returns the number of samples in each bin.
If True, returns the probability *density* function at the bin,
``bin_count / sample_count / bin_volume``.
weights : (N,) array_like, optional
An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`.
Weights are normalized to 1 if density is True. If density is False,
the values of the returned histogram are equal to the sum of the
weights belonging to the samples falling into each bin.
Returns
-------
H : ndarray
The multidimensional histogram of sample x. See density and weights
for the different possible semantics.
edges : tuple of ndarrays
A tuple of D arrays describing the bin edges for each dimension.
See Also
--------
histogram: 1-D histogram
histogram2d: 2-D histogram
Examples
--------
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> r = rng.normal(size=(100,3))
>>> H, edges = np.histogramdd(r, bins = (5, 8, 4))
>>> H.shape, edges[0].size, edges[1].size, edges[2].size
((5, 8, 4), 6, 9, 5)
numpy.hsplit
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
hsplit(ary, indices_or_sections)
Split an array into multiple sub-arrays horizontally (column-wise).
Please refer to the `split` documentation. `hsplit` is equivalent
to `split` with ``axis=1``, the array is always split along the second
axis except for 1-D arrays, where it is split at ``axis=0``.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> import numpy as np
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.]])
>>> np.hsplit(x, 2)
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
[12., 13.]]),
array([[ 2., 3.],
[ 6., 7.],
[10., 11.],
[14., 15.]])]
>>> np.hsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2.],
[ 4., 5., 6.],
[ 8., 9., 10.],
[12., 13., 14.]]),
array([[ 3.],
[ 7.],
[11.],
[15.]]),
array([], shape=(4, 0), dtype=float64)]
With a higher dimensional array the split is still along the second axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[0., 1.],
[2., 3.]],
[[4., 5.],
[6., 7.]]])
>>> np.hsplit(x, 2)
[array([[[0., 1.]],
[[4., 5.]]]),
array([[[2., 3.]],
[[6., 7.]]])]
With a 1-D array, the split is along axis 0.
>>> x = np.array([0, 1, 2, 3, 4, 5])
>>> np.hsplit(x, 2)
[array([0, 1, 2]), array([3, 4, 5])]
numpy.hstack
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
hstack(tup, *, dtype=None, casting='same_kind')
Stack arrays in sequence horizontally (column wise).
This is equivalent to concatenation along the second axis, except for 1-D
arrays where it concatenates along the first axis. Rebuilds arrays divided
by `hsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of ndarrays
The arrays must have the same shape along all but the second axis,
except 1-D arrays which can be any length.
dtype : str or dtype
If provided, the destination array will have this dtype. Cannot be
provided together with `out`.
.. versionadded:: 1.24
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'same_kind'.
.. versionadded:: 1.24
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays.
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
block : Assemble an nd-array from nested lists of blocks.
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third axis).
column_stack : Stack 1-D arrays as columns into a 2-D array.
hsplit : Split an array into multiple sub-arrays
horizontally (column-wise).
unstack : Split an array into a tuple of sub-arrays along an axis.
Examples
--------
>>> import numpy as np
>>> a = np.array((1,2,3))
>>> b = np.array((4,5,6))
>>> np.hstack((a,b))
array([1, 2, 3, 4, 5, 6])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[4],[5],[6]])
>>> np.hstack((a,b))
array([[1, 4],
[2, 5],
[3, 6]])
numpy.hypot
Python Library Documentation: ufunc
hypot = <ufunc 'hypot'>
hypot(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Given the "legs" of a right triangle, return its hypotenuse.
Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or
`x2` is scalar_like (i.e., unambiguously cast-able to a scalar type),
it is broadcast for use with each element of the other argument.
(See Examples)
Parameters
----------
x1, x2 : array_like
Leg of the triangle(s).
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
z : ndarray
The hypotenuse of the triangle(s).
This is a scalar if both `x1` and `x2` are scalars.
Examples
--------
>>> import numpy as np
>>> np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3)))
array([[ 5., 5., 5.],
[ 5., 5., 5.],
[ 5., 5., 5.]])
Example showing broadcast of scalar_like argument:
>>> np.hypot(3*np.ones((3, 3)), [4])
array([[ 5., 5., 5.],
[ 5., 5., 5.],
[ 5., 5., 5.]])
numpy.i0
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
i0(x)
Modified Bessel function of the first kind, order 0.
Usually denoted :math:`I_0`.
Parameters
----------
x : array_like of float
Argument of the Bessel function.
Returns
-------
out : ndarray, shape = x.shape, dtype = float
The modified Bessel function evaluated at each of the elements of `x`.
See Also
--------
scipy.special.i0, scipy.special.iv, scipy.special.ive
Notes
-----
The scipy implementation is recommended over this function: it is a
proper ufunc written in C, and more than an order of magnitude faster.
We use the algorithm published by Clenshaw [1]_ and referenced by
Abramowitz and Stegun [2]_, for which the function domain is
partitioned into the two intervals [0,8] and (8,inf), and Chebyshev
polynomial expansions are employed in each interval. Relative error on
the domain [0,30] using IEEE arithmetic is documented [3]_ as having a
peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000).
References
----------
.. [1] C. W. Clenshaw, "Chebyshev series for mathematical functions", in
*National Physical Laboratory Mathematical Tables*, vol. 5, London:
Her Majesty's Stationery Office, 1962.
.. [2] M. Abramowitz and I. A. Stegun, *Handbook of Mathematical
Functions*, 10th printing, New York: Dover, 1964, pp. 379.
https://personal.math.ubc.ca/~cbm/aands/page_379.htm
.. [3] https://metacpan.org/pod/distribution/Math-Cephes/lib/Math/Cephes.pod#i0:-Modified-Bessel-function-of-order-zero
Examples
--------
>>> import numpy as np
>>> np.i0(0.)
array(1.0)
>>> np.i0([0, 1, 2, 3])
array([1. , 1.26606588, 2.2795853 , 4.88079259])
numpy.identity
Python Library Documentation: function identity in module numpy
identity(n, dtype=None, *, like=None)
Return the identity array.
The identity array is a square array with ones on
the main diagonal.
Parameters
----------
n : int
Number of rows (and columns) in `n` x `n` output.
dtype : data-type, optional
Data-type of the output. Defaults to ``float``.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
`n` x `n` array with its main diagonal set to one,
and all other elements 0.
Examples
--------
>>> import numpy as np
>>> np.identity(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
numpy.iinfo
Python Library Documentation: class iinfo in module numpy class iinfo(builtins.object) | iinfo(int_type) | | iinfo(type) | | Machine limits for integer types. | | Attributes | ---------- | bits : int | The number of bits occupied by the type. | dtype : dtype | Returns the dtype for which `iinfo` returns information. | min : int | The smallest integer expressible by the type. | max : int | The largest integer expressible by the type. | | Parameters | ---------- | int_type : integer type, dtype, or instance | The kind of integer data type to get information about. | | See Also | -------- | finfo : The equivalent for floating point data types. | | Examples | -------- | With types: | | >>> import numpy as np | >>> ii16 = np.iinfo(np.int16) | >>> ii16.min | -32768 | >>> ii16.max | 32767 | >>> ii32 = np.iinfo(np.int32) | >>> ii32.min | -2147483648 | >>> ii32.max | 2147483647 | | With instances: | | >>> ii32 = np.iinfo(np.int32(10)) | >>> ii32.min | -2147483648 | >>> ii32.max | 2147483647 | | Methods defined here: | | __init__(self, int_type) from numpy._core.getlimits.iinfo | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) from numpy._core.getlimits.iinfo | Return repr(self). | | __str__(self) from numpy._core.getlimits.iinfo | String representation. | | ---------------------------------------------------------------------- | Readonly properties defined here: | | max | Maximum value of given dtype. | | min | Minimum value of given dtype. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
numpy.imag
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
imag(val)
Return the imaginary part of the complex argument.
Parameters
----------
val : array_like
Input array.
Returns
-------
out : ndarray or scalar
The imaginary component of the complex argument. If `val` is real,
the type of `val` is used for the output. If `val` has complex
elements, the returned type is float.
See Also
--------
real, angle, real_if_close
Examples
--------
>>> import numpy as np
>>> a = np.array([1+2j, 3+4j, 5+6j])
>>> a.imag
array([2., 4., 6.])
>>> a.imag = np.array([8, 10, 12])
>>> a
array([1. +8.j, 3.+10.j, 5.+12.j])
>>> np.imag(1 + 1j)
1.0
numpy.in1d
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
in1d(ar1, ar2, assume_unique=False, invert=False, *, kind=None)
Test whether each element of a 1-D array is also present in a second array.
.. deprecated:: 2.0
Use :func:`isin` instead of `in1d` for new code.
Returns a boolean array the same length as `ar1` that is True
where an element of `ar1` is in `ar2` and False otherwise.
Parameters
----------
ar1 : (M,) array_like
Input array.
ar2 : array_like
The values against which to test each value of `ar1`.
assume_unique : bool, optional
If True, the input arrays are both assumed to be unique, which
can speed up the calculation. Default is False.
invert : bool, optional
If True, the values in the returned array are inverted (that is,
False where an element of `ar1` is in `ar2` and True otherwise).
Default is False. ``np.in1d(a, b, invert=True)`` is equivalent
to (but is faster than) ``np.invert(in1d(a, b))``.
kind : {None, 'sort', 'table'}, optional
The algorithm to use. This will not affect the final result,
but will affect the speed and memory use. The default, None,
will select automatically based on memory considerations.
* If 'sort', will use a mergesort-based approach. This will have
a memory usage of roughly 6 times the sum of the sizes of
`ar1` and `ar2`, not accounting for size of dtypes.
* If 'table', will use a lookup table approach similar
to a counting sort. This is only available for boolean and
integer arrays. This will have a memory usage of the
size of `ar1` plus the max-min value of `ar2`. `assume_unique`
has no effect when the 'table' option is used.
* If None, will automatically choose 'table' if
the required memory allocation is less than or equal to
6 times the sum of the sizes of `ar1` and `ar2`,
otherwise will use 'sort'. This is done to not use
a large amount of memory by default, even though
'table' may be faster in most cases. If 'table' is chosen,
`assume_unique` will have no effect.
.. versionadded:: 1.8.0
Returns
-------
in1d : (M,) ndarray, bool
The values `ar1[in1d]` are in `ar2`.
See Also
--------
isin : Version of this function that preserves the
shape of ar1.
Notes
-----
`in1d` can be considered as an element-wise function version of the
python keyword `in`, for 1-D sequences. ``in1d(a, b)`` is roughly
equivalent to ``np.array([item in b for item in a])``.
However, this idea fails if `ar2` is a set, or similar (non-sequence)
container: As ``ar2`` is converted to an array, in those cases
``asarray(ar2)`` is an object array rather than the expected array of
contained values.
Using ``kind='table'`` tends to be faster than `kind='sort'` if the
following relationship is true:
``log10(len(ar2)) > (log10(max(ar2)-min(ar2)) - 2.27) / 0.927``,
but may use greater memory. The default value for `kind` will
be automatically selected based only on memory usage, so one may
manually set ``kind='table'`` if memory constraints can be relaxed.
.. versionadded:: 1.4.0
Examples
--------
>>> import numpy as np
>>> test = np.array([0, 1, 2, 5, 0])
>>> states = [0, 2]
>>> mask = np.in1d(test, states)
>>> mask
array([ True, False, True, False, True])
>>> test[mask]
array([0, 2, 0])
>>> mask = np.in1d(test, states, invert=True)
>>> mask
array([False, True, False, True, False])
>>> test[mask]
array([1, 5])
numpy.index_exp
Python Library Documentation: IndexExpression in module numpy.lib._index_tricks_impl object class IndexExpression(builtins.object) | IndexExpression(maketuple) | | A nicer way to build up index tuples for arrays. | | .. note:: | Use one of the two predefined instances ``index_exp`` or `s_` | rather than directly using `IndexExpression`. | | For any index combination, including slicing and axis insertion, | ``a[indices]`` is the same as ``a[np.index_exp[indices]]`` for any | array `a`. However, ``np.index_exp[indices]`` can be used anywhere | in Python code and returns a tuple of slice objects that can be | used in the construction of complex index expressions. | | Parameters | ---------- | maketuple : bool | If True, always returns a tuple. | | See Also | -------- | s_ : Predefined instance without tuple conversion: | `s_ = IndexExpression(maketuple=False)`. | The ``index_exp`` is another predefined instance that | always returns a tuple: | `index_exp = IndexExpression(maketuple=True)`. | | Notes | ----- | You can do all this with :class:`slice` plus a few special objects, | but there's a lot to remember and this version is simpler because | it uses the standard array indexing syntax. | | Examples | -------- | >>> import numpy as np | >>> np.s_[2::2] | slice(2, None, 2) | >>> np.index_exp[2::2] | (slice(2, None, 2),) | | >>> np.array([0, 1, 2, 3, 4])[np.s_[2::2]] | array([2, 4]) | | Methods defined here: | | __getitem__(self, item) | | __init__(self, maketuple) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | maketuple
numpy.indices
Python Library Documentation: function indices in module numpy
indices(dimensions, dtype=<class 'int'>, sparse=False)
Return an array representing the indices of a grid.
Compute an array where the subarrays contain index values 0, 1, ...
varying only along the corresponding axis.
Parameters
----------
dimensions : sequence of ints
The shape of the grid.
dtype : dtype, optional
Data type of the result.
sparse : boolean, optional
Return a sparse representation of the grid instead of a dense
representation. Default is False.
.. versionadded:: 1.17
Returns
-------
grid : one ndarray or tuple of ndarrays
If sparse is False:
Returns one array of grid indices,
``grid.shape = (len(dimensions),) + tuple(dimensions)``.
If sparse is True:
Returns a tuple of arrays, with
``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
dimensions[i] in the ith place
See Also
--------
mgrid, ogrid, meshgrid
Notes
-----
The output shape in the dense case is obtained by prepending the number
of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
``(N, r0, ..., rN-1)``.
The subarrays ``grid[k]`` contains the N-D array of indices along the
``k-th`` axis. Explicitly::
grid[k, i0, i1, ..., iN-1] = ik
Examples
--------
>>> import numpy as np
>>> grid = np.indices((2, 3))
>>> grid.shape
(2, 2, 3)
>>> grid[0] # row indices
array([[0, 0, 0],
[1, 1, 1]])
>>> grid[1] # column indices
array([[0, 1, 2],
[0, 1, 2]])
The indices can be used as an index into an array.
>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0, 1, 2],
[4, 5, 6]])
Note that it would be more straightforward in the above example to
extract the required elements directly with ``x[:2, :3]``.
If sparse is set to true, the grid will be returned in a sparse
representation.
>>> i, j = np.indices((2, 3), sparse=True)
>>> i.shape
(2, 1)
>>> j.shape
(1, 3)
>>> i # row indices
array([[0],
[1]])
>>> j # column indices
array([[0, 1, 2]])
numpy.inexact
Python Library Documentation: class inexact in module numpy class inexact(number) | Abstract base class of all numeric scalar types with a (potentially) | inexact representation of the values in its range, such as | floating-point numbers. | | Method resolution order: | inexact | number | generic | builtins.object | | Class methods inherited from number: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Data and other attributes inherited from generic: | | __hash__ = None
numpy.inf
Python Library Documentation: float object
class float(object)
| float(x=0, /)
|
| Convert a string or number to a floating-point number, if possible.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(self, /)
| Return the ceiling as an Integral.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(self, /)
| Return the floor as an Integral.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Formats the float according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __round__(self, ndigits=None, /)
| Return the Integral closest to x, rounding half toward even.
|
| When an argument is passed, work like built-in round(x, ndigits).
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| as_integer_ratio(self, /)
| Return a pair of integers, whose ratio is exactly equal to the original float.
|
| The ratio is in lowest terms and has a positive denominator. Raise
| OverflowError on infinities and a ValueError on NaNs.
|
| >>> (10.0).as_integer_ratio()
| (10, 1)
| >>> (0.0).as_integer_ratio()
| (0, 1)
| >>> (-.25).as_integer_ratio()
| (-1, 4)
|
| conjugate(self, /)
| Return self, the complex conjugate of any float.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> 3.14159.hex()
| '0x1.921f9f01b866ep+1'
|
| is_integer(self, /)
| Return True if the float is an integer.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __getformat__(typestr, /)
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
| little-endian' best describes the format of floating-point numbers used by the
| C type named by typestr.
|
| fromhex(string, /)
| Create a floating-point number from a hexadecimal string.
|
| >>> float.fromhex('0x1.ffffp10')
| 2047.984375
| >>> float.fromhex('-0x1p-1074')
| -5e-324
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| imag
| the imaginary part of a complex number
|
| real
| the real part of a complex number
numpy.info
Python Library Documentation: function info in module numpy
info(object=None, maxwidth=76, output=None, toplevel='numpy')
Get help information for an array, function, class, or module.
Parameters
----------
object : object or str, optional
Input object or name to get information about. If `object` is
an `ndarray` instance, information about the array is printed.
If `object` is a numpy object, its docstring is given. If it is
a string, available modules are searched for matching objects.
If None, information about `info` itself is returned.
maxwidth : int, optional
Printing width.
output : file like object, optional
File like object that the output is written to, default is
``None``, in which case ``sys.stdout`` will be used.
The object has to be opened in 'w' or 'a' mode.
toplevel : str, optional
Start search at this level.
Notes
-----
When used interactively with an object, ``np.info(obj)`` is equivalent
to ``help(obj)`` on the Python prompt or ``obj?`` on the IPython
prompt.
Examples
--------
>>> np.info(np.polyval) # doctest: +SKIP
polyval(p, x)
Evaluate the polynomial p at x.
...
When using a string for `object` it is possible to get multiple results.
>>> np.info('fft') # doctest: +SKIP
*** Found in numpy ***
Core FFT routines
...
*** Found in numpy.fft ***
fft(a, n=None, axis=-1)
...
*** Repeat reference found in numpy.fft.fftpack ***
*** Total of 3 references found. ***
When the argument is an array, information about the array is printed.
>>> a = np.array([[1 + 2j, 3, -4], [-5j, 6, 0]], dtype=np.complex64)
>>> np.info(a)
class: ndarray
shape: (2, 3)
strides: (24, 8)
itemsize: 8
aligned: True
contiguous: True
fortran: False
data pointer: 0x562b6e0d2860 # may vary
byteorder: little
byteswap: False
type: complex64
numpy.inner
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
inner(...)
inner(a, b, /)
Inner product of two arrays.
Ordinary inner product of vectors for 1-D arrays (without complex
conjugation), in higher dimensions a sum product over the last axes.
Parameters
----------
a, b : array_like
If `a` and `b` are nonscalar, their last dimensions must match.
Returns
-------
out : ndarray
If `a` and `b` are both
scalars or both 1-D arrays then a scalar is returned; otherwise
an array is returned.
``out.shape = (*a.shape[:-1], *b.shape[:-1])``
Raises
------
ValueError
If both `a` and `b` are nonscalar and their last dimensions have
different sizes.
See Also
--------
tensordot : Sum products over arbitrary axes.
dot : Generalised matrix product, using second last dimension of `b`.
einsum : Einstein summation convention.
Notes
-----
For vectors (1-D arrays) it computes the ordinary inner-product::
np.inner(a, b) = sum(a[:]*b[:])
More generally, if ``ndim(a) = r > 0`` and ``ndim(b) = s > 0``::
np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1))
or explicitly::
np.inner(a, b)[i0,...,ir-2,j0,...,js-2]
= sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:])
In addition `a` or `b` may be scalars, in which case::
np.inner(a,b) = a*b
Examples
--------
Ordinary inner product for vectors:
>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
2
Some multidimensional examples:
>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> c = np.inner(a, b)
>>> c.shape
(2, 3)
>>> c
array([[ 14, 38, 62],
[ 86, 110, 134]])
>>> a = np.arange(2).reshape((1,1,2))
>>> b = np.arange(6).reshape((3,2))
>>> c = np.inner(a, b)
>>> c.shape
(1, 1, 3)
>>> c
array([[[1, 3, 5]]])
An example where `b` is a scalar:
>>> np.inner(np.eye(2), 7)
array([[7., 0.],
[0., 7.]])
numpy.insert
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
insert(arr, obj, values, axis=None)
Insert values along the given axis before the given indices.
Parameters
----------
arr : array_like
Input array.
obj : int, slice or sequence of ints
Object that defines the index or indices before which `values` is
inserted.
.. versionadded:: 1.8.0
Support for multiple insertions when `obj` is a single scalar or a
sequence with one element (similar to calling insert multiple
times).
values : array_like
Values to insert into `arr`. If the type of `values` is different
from that of `arr`, `values` is converted to the type of `arr`.
`values` should be shaped so that ``arr[...,obj,...] = values``
is legal.
axis : int, optional
Axis along which to insert `values`. If `axis` is None then `arr`
is flattened first.
Returns
-------
out : ndarray
A copy of `arr` with `values` inserted. Note that `insert`
does not occur in-place: a new array is returned. If
`axis` is None, `out` is a flattened array.
See Also
--------
append : Append elements at the end of an array.
concatenate : Join a sequence of arrays along an existing axis.
delete : Delete elements from an array.
Notes
-----
Note that for higher dimensional inserts ``obj=0`` behaves very different
from ``obj=[0]`` just like ``arr[:,0,:] = values`` is different from
``arr[:,[0],:] = values``. This is because of the difference between basic
and advanced :ref:`indexing <basics.indexing>`.
Examples
--------
>>> import numpy as np
>>> a = np.arange(6).reshape(3, 2)
>>> a
array([[0, 1],
[2, 3],
[4, 5]])
>>> np.insert(a, 1, 6)
array([0, 6, 1, 2, 3, 4, 5])
>>> np.insert(a, 1, 6, axis=1)
array([[0, 6, 1],
[2, 6, 3],
[4, 6, 5]])
Difference between sequence and scalars,
showing how ``obj=[1]`` behaves different from ``obj=1``:
>>> np.insert(a, [1], [[7],[8],[9]], axis=1)
array([[0, 7, 1],
[2, 8, 3],
[4, 9, 5]])
>>> np.insert(a, 1, [[7],[8],[9]], axis=1)
array([[0, 7, 8, 9, 1],
[2, 7, 8, 9, 3],
[4, 7, 8, 9, 5]])
>>> np.array_equal(np.insert(a, 1, [7, 8, 9], axis=1),
... np.insert(a, [1], [[7],[8],[9]], axis=1))
True
>>> b = a.flatten()
>>> b
array([0, 1, 2, 3, 4, 5])
>>> np.insert(b, [2, 2], [6, 7])
array([0, 1, 6, 7, 2, 3, 4, 5])
>>> np.insert(b, slice(2, 4), [7, 8])
array([0, 1, 7, 2, 8, 3, 4, 5])
>>> np.insert(b, [2, 2], [7.13, False]) # type casting
array([0, 1, 7, 0, 2, 3, 4, 5])
>>> x = np.arange(8).reshape(2, 4)
>>> idx = (1, 3)
>>> np.insert(x, idx, 999, axis=1)
array([[ 0, 999, 1, 2, 999, 3],
[ 4, 999, 5, 6, 999, 7]])
numpy.int16
Python Library Documentation: class int16 in module numpy class int16(signedinteger) | Signed integer type, compatible with C ``short``. | | :Character code: ``'h'`` | :Canonical name: `numpy.short` | :Alias on this platform (win32 AMD64): `numpy.int16`: 16-bit signed integer (``-32_768`` to ``32_767``). | | Method resolution order: | int16 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | int16.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.int16(127).bit_count() | 7 | >>> np.int16(-127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.int32
Python Library Documentation: class int32 in module numpy class int32(signedinteger) | Method resolution order: | int32 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | int32.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.int32(127).bit_count() | 7 | >>> np.int32(-127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.int64
Python Library Documentation: class int64 in module numpy class int64(signedinteger) | Default signed integer type, 64bit on 64bit systems and 32bit on 32bit | systems. | | :Character code: ``'q'`` | :Canonical name: `numpy.int_` | :Alias on this platform (win32 AMD64): `numpy.int64`: 64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``). | :Alias on this platform (win32 AMD64): `numpy.intp`: Signed integer large enough to fit pointer, compatible with C ``intptr_t``. | | Method resolution order: | int64 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | int64.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.int64(127).bit_count() | 7 | >>> np.int64(-127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.int8
Python Library Documentation: class int8 in module numpy class int8(signedinteger) | Signed integer type, compatible with C ``char``. | | :Character code: ``'b'`` | :Canonical name: `numpy.byte` | :Alias on this platform (win32 AMD64): `numpy.int8`: 8-bit signed integer (``-128`` to ``127``). | | Method resolution order: | int8 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | int8.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.int8(127).bit_count() | 7 | >>> np.int8(-127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.int_
Python Library Documentation: class int64 in module numpy class int64(signedinteger) | Default signed integer type, 64bit on 64bit systems and 32bit on 32bit | systems. | | :Character code: ``'q'`` | :Canonical name: `numpy.int_` | :Alias on this platform (win32 AMD64): `numpy.int64`: 64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``). | :Alias on this platform (win32 AMD64): `numpy.intp`: Signed integer large enough to fit pointer, compatible with C ``intptr_t``. | | Method resolution order: | int64 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | int64.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.int64(127).bit_count() | 7 | >>> np.int64(-127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.intc
Python Library Documentation: class intc in module numpy class intc(signedinteger) | Signed integer type, compatible with C ``int``. | | :Character code: ``'i'`` | | Method resolution order: | intc | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.integer
Python Library Documentation: class integer in module numpy class integer(number) | Abstract base class of all integer scalar types. | | Method resolution order: | integer | number | generic | builtins.object | | Methods defined here: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors defined here: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Class methods inherited from number: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Data and other attributes inherited from generic: | | __hash__ = None
numpy.interp
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
interp(x, xp, fp, left=None, right=None, period=None)
One-dimensional linear interpolation for monotonically increasing sample points.
Returns the one-dimensional piecewise linear interpolant to a function
with given discrete data points (`xp`, `fp`), evaluated at `x`.
Parameters
----------
x : array_like
The x-coordinates at which to evaluate the interpolated values.
xp : 1-D sequence of floats
The x-coordinates of the data points, must be increasing if argument
`period` is not specified. Otherwise, `xp` is internally sorted after
normalizing the periodic boundaries with ``xp = xp % period``.
fp : 1-D sequence of float or complex
The y-coordinates of the data points, same length as `xp`.
left : optional float or complex corresponding to fp
Value to return for `x < xp[0]`, default is `fp[0]`.
right : optional float or complex corresponding to fp
Value to return for `x > xp[-1]`, default is `fp[-1]`.
period : None or float, optional
A period for the x-coordinates. This parameter allows the proper
interpolation of angular x-coordinates. Parameters `left` and `right`
are ignored if `period` is specified.
.. versionadded:: 1.10.0
Returns
-------
y : float or complex (corresponding to fp) or ndarray
The interpolated values, same shape as `x`.
Raises
------
ValueError
If `xp` and `fp` have different length
If `xp` or `fp` are not 1-D sequences
If `period == 0`
See Also
--------
scipy.interpolate
Warnings
--------
The x-coordinate sequence is expected to be increasing, but this is not
explicitly enforced. However, if the sequence `xp` is non-increasing,
interpolation results are meaningless.
Note that, since NaN is unsortable, `xp` also cannot contain NaNs.
A simple check for `xp` being strictly increasing is::
np.all(np.diff(xp) > 0)
Examples
--------
>>> import numpy as np
>>> xp = [1, 2, 3]
>>> fp = [3, 2, 0]
>>> np.interp(2.5, xp, fp)
1.0
>>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
array([3. , 3. , 2.5 , 0.56, 0. ])
>>> UNDEF = -99.0
>>> np.interp(3.14, xp, fp, right=UNDEF)
-99.0
Plot an interpolant to the sine function:
>>> x = np.linspace(0, 2*np.pi, 10)
>>> y = np.sin(x)
>>> xvals = np.linspace(0, 2*np.pi, 50)
>>> yinterp = np.interp(xvals, x, y)
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(xvals, yinterp, '-x')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.show()
Interpolation with periodic x-coordinates:
>>> x = [-180, -170, -185, 185, -10, -5, 0, 365]
>>> xp = [190, -190, 350, -350]
>>> fp = [5, 10, 3, 4]
>>> np.interp(x, xp, fp, period=360)
array([7.5 , 5. , 8.75, 6.25, 3. , 3.25, 3.5 , 3.75])
Complex interpolation:
>>> x = [1.5, 4.0]
>>> xp = [2,3,5]
>>> fp = [1.0j, 0, 2+3j]
>>> np.interp(x, xp, fp)
array([0.+1.j , 1.+1.5j])
numpy.intersect1d
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
intersect1d(ar1, ar2, assume_unique=False, return_indices=False)
Find the intersection of two arrays.
Return the sorted, unique values that are in both of the input arrays.
Parameters
----------
ar1, ar2 : array_like
Input arrays. Will be flattened if not already 1D.
assume_unique : bool
If True, the input arrays are both assumed to be unique, which
can speed up the calculation. If True but ``ar1`` or ``ar2`` are not
unique, incorrect results and out-of-bounds indices could result.
Default is False.
return_indices : bool
If True, the indices which correspond to the intersection of the two
arrays are returned. The first instance of a value is used if there are
multiple. Default is False.
.. versionadded:: 1.15.0
Returns
-------
intersect1d : ndarray
Sorted 1D array of common and unique elements.
comm1 : ndarray
The indices of the first occurrences of the common values in `ar1`.
Only provided if `return_indices` is True.
comm2 : ndarray
The indices of the first occurrences of the common values in `ar2`.
Only provided if `return_indices` is True.
Examples
--------
>>> import numpy as np
>>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
array([1, 3])
To intersect more than two arrays, use functools.reduce:
>>> from functools import reduce
>>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
array([3])
To return the indices of the values common to the input arrays
along with the intersected values:
>>> x = np.array([1, 1, 2, 3, 4])
>>> y = np.array([2, 1, 4, 6])
>>> xy, x_ind, y_ind = np.intersect1d(x, y, return_indices=True)
>>> x_ind, y_ind
(array([0, 2, 4]), array([1, 0, 2]))
>>> xy, x[x_ind], y[y_ind]
(array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4]))
numpy.intp
Python Library Documentation: class int64 in module numpy class int64(signedinteger) | Default signed integer type, 64bit on 64bit systems and 32bit on 32bit | systems. | | :Character code: ``'q'`` | :Canonical name: `numpy.int_` | :Alias on this platform (win32 AMD64): `numpy.int64`: 64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``). | :Alias on this platform (win32 AMD64): `numpy.intp`: Signed integer large enough to fit pointer, compatible with C ``intptr_t``. | | Method resolution order: | int64 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | int64.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.int64(127).bit_count() | 7 | >>> np.int64(-127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.invert
Python Library Documentation: ufunc
invert = <ufunc 'invert'>
invert(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute bit-wise inversion, or bit-wise NOT, element-wise.
Computes the bit-wise NOT of the underlying binary representation of
the integers in the input arrays. This ufunc implements the C/Python
operator ``~``.
For signed integer inputs, the bit-wise NOT of the absolute value is
returned. In a two's-complement system, this operation effectively flips
all the bits, resulting in a representation that corresponds to the
negative of the input plus one. This is the most common method of
representing signed integers on computers [1]_. A N-bit two's-complement
system can represent every integer in the range :math:`-2^{N-1}` to
:math:`+2^{N-1}-1`.
Parameters
----------
x : array_like
Only integer and boolean types are handled.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Result.
This is a scalar if `x` is a scalar.
See Also
--------
bitwise_and, bitwise_or, bitwise_xor
logical_not
binary_repr :
Return the binary representation of the input number as a string.
Notes
-----
``numpy.bitwise_not`` is an alias for `invert`:
>>> np.bitwise_not is np.invert
True
References
----------
.. [1] Wikipedia, "Two's complement",
https://en.wikipedia.org/wiki/Two's_complement
Examples
--------
>>> import numpy as np
We've seen that 13 is represented by ``00001101``.
The invert or bit-wise NOT of 13 is then:
>>> x = np.invert(np.array(13, dtype=np.uint8))
>>> x
242
>>> np.binary_repr(x, width=8)
'11110010'
The result depends on the bit-width:
>>> x = np.invert(np.array(13, dtype=np.uint16))
>>> x
65522
>>> np.binary_repr(x, width=16)
'1111111111110010'
When using signed integer types, the result is the bit-wise NOT of
the unsigned type, interpreted as a signed integer:
>>> np.invert(np.array([13], dtype=np.int8))
array([-14], dtype=int8)
>>> np.binary_repr(-14, width=8)
'11110010'
Booleans are accepted as well:
>>> np.invert(np.array([True, False]))
array([False, True])
The ``~`` operator can be used as a shorthand for ``np.invert`` on
ndarrays.
>>> x1 = np.array([True, False])
>>> ~x1
array([False, True])
numpy.is_busday
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
is_busday(...)
is_busday(
dates,
weekmask='1111100',
holidays=None,
busdaycal=None,
out=None
)
Calculates which of the given dates are valid days, and which are not.
.. versionadded:: 1.7.0
Parameters
----------
dates : array_like of datetime64[D]
The array of dates to process.
weekmask : str or array_like of bool, optional
A seven-element array indicating which of Monday through Sunday are
valid days. May be specified as a length-seven list or array, like
[1,1,1,1,1,0,0]; a length-seven string, like '1111100'; or a string
like "Mon Tue Wed Thu Fri", made up of 3-character abbreviations for
weekdays, optionally separated by white space. Valid abbreviations
are: Mon Tue Wed Thu Fri Sat Sun
holidays : array_like of datetime64[D], optional
An array of dates to consider as invalid dates. They may be
specified in any order, and NaT (not-a-time) dates are ignored.
This list is saved in a normalized form that is suited for
fast calculations of valid days.
busdaycal : busdaycalendar, optional
A `busdaycalendar` object which specifies the valid days. If this
parameter is provided, neither weekmask nor holidays may be
provided.
out : array of bool, optional
If provided, this array is filled with the result.
Returns
-------
out : array of bool
An array with the same shape as ``dates``, containing True for
each valid day, and False for each invalid day.
See Also
--------
busdaycalendar : An object that specifies a custom set of valid days.
busday_offset : Applies an offset counted in valid days.
busday_count : Counts how many valid days are in a half-open date range.
Examples
--------
>>> import numpy as np
>>> # The weekdays are Friday, Saturday, and Monday
... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'],
... holidays=['2011-07-01', '2011-07-04', '2011-07-17'])
array([False, False, True])
numpy.isclose
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
Returns a boolean array where two arrays are element-wise equal within a
tolerance.
The tolerance values are positive, typically very small numbers. The
relative difference (`rtol` * abs(`b`)) and the absolute difference
`atol` are added together to compare against the absolute difference
between `a` and `b`.
.. warning:: The default `atol` is not appropriate for comparing numbers
with magnitudes much smaller than one (see Notes).
Parameters
----------
a, b : array_like
Input arrays to compare.
rtol : array_like
The relative tolerance parameter (see Notes).
atol : array_like
The absolute tolerance parameter (see Notes).
equal_nan : bool
Whether to compare NaN's as equal. If True, NaN's in `a` will be
considered equal to NaN's in `b` in the output array.
Returns
-------
y : array_like
Returns a boolean array of where `a` and `b` are equal within the
given tolerance. If both `a` and `b` are scalars, returns a single
boolean value.
See Also
--------
allclose
math.isclose
Notes
-----
.. versionadded:: 1.7.0
For finite values, isclose uses the following equation to test whether
two floating point values are equivalent.::
absolute(a - b) <= (atol + rtol * absolute(b))
Unlike the built-in `math.isclose`, the above equation is not symmetric
in `a` and `b` -- it assumes `b` is the reference value -- so that
`isclose(a, b)` might be different from `isclose(b, a)`.
The default value of `atol` is not appropriate when the reference value
`b` has magnitude smaller than one. For example, it is unlikely that
``a = 1e-9`` and ``b = 2e-9`` should be considered "close", yet
``isclose(1e-9, 2e-9)`` is ``True`` with default settings. Be sure
to select `atol` for the use case at hand, especially for defining the
threshold below which a non-zero value in `a` will be considered "close"
to a very small or zero value in `b`.
`isclose` is not defined for non-numeric data types.
:class:`bool` is considered a numeric data-type for this purpose.
Examples
--------
>>> import numpy as np
>>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
array([ True, False])
>>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
array([ True, True])
>>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
array([False, True])
>>> np.isclose([1.0, np.nan], [1.0, np.nan])
array([ True, False])
>>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
array([ True, True])
>>> np.isclose([1e-8, 1e-7], [0.0, 0.0])
array([ True, False])
>>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0)
array([False, False])
>>> np.isclose([1e-10, 1e-10], [1e-20, 0.0])
array([ True, True])
>>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0)
array([False, True])
numpy.iscomplex
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
iscomplex(x)
Returns a bool array, where True if input element is complex.
What is tested is whether the input has a non-zero imaginary part, not if
the input type is complex.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray of bools
Output array.
See Also
--------
isreal
iscomplexobj : Return True if x is a complex type or an array of complex
numbers.
Examples
--------
>>> import numpy as np
>>> np.iscomplex([1+1j, 1+0j, 4.5, 3, 2, 2j])
array([ True, False, False, False, False, True])
numpy.iscomplexobj
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
iscomplexobj(x)
Check for a complex type or an array of complex numbers.
The type of the input is checked, not the value. Even if the input
has an imaginary part equal to zero, `iscomplexobj` evaluates to True.
Parameters
----------
x : any
The input can be of any type and shape.
Returns
-------
iscomplexobj : bool
The return value, True if `x` is of a complex type or has at least
one complex element.
See Also
--------
isrealobj, iscomplex
Examples
--------
>>> import numpy as np
>>> np.iscomplexobj(1)
False
>>> np.iscomplexobj(1+0j)
True
>>> np.iscomplexobj([3, 1+0j, True])
True
numpy.isdtype
Python Library Documentation: function isdtype in module numpy
isdtype(dtype, kind)
Determine if a provided dtype is of a specified data type ``kind``.
This function only supports built-in NumPy's data types.
Third-party dtypes are not yet supported.
Parameters
----------
dtype : dtype
The input dtype.
kind : dtype or str or tuple of dtypes/strs.
dtype or dtype kind. Allowed dtype kinds are:
* ``'bool'`` : boolean kind
* ``'signed integer'`` : signed integer data types
* ``'unsigned integer'`` : unsigned integer data types
* ``'integral'`` : integer data types
* ``'real floating'`` : real-valued floating-point data types
* ``'complex floating'`` : complex floating-point data types
* ``'numeric'`` : numeric data types
Returns
-------
out : bool
See Also
--------
issubdtype
Examples
--------
>>> import numpy as np
>>> np.isdtype(np.float32, np.float64)
False
>>> np.isdtype(np.float32, "real floating")
True
>>> np.isdtype(np.complex128, ("real floating", "complex floating"))
True
numpy.isfinite
Python Library Documentation: ufunc
isfinite = <ufunc 'isfinite'>
isfinite(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Test element-wise for finiteness (not infinity and not Not a Number).
The result is returned as a boolean array.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray, bool
True where ``x`` is not positive infinity, negative infinity,
or NaN; false otherwise.
This is a scalar if `x` is a scalar.
See Also
--------
isinf, isneginf, isposinf, isnan
Notes
-----
Not a Number, positive infinity and negative infinity are considered
to be non-finite.
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. Errors result if the
second argument is also supplied when `x` is a scalar input, or if
first and second arguments have different shapes.
Examples
--------
>>> import numpy as np
>>> np.isfinite(1)
True
>>> np.isfinite(0)
True
>>> np.isfinite(np.nan)
False
>>> np.isfinite(np.inf)
False
>>> np.isfinite(-np.inf)
False
>>> np.isfinite([np.log(-1.),1.,np.log(0)])
array([False, True, False])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([2, 2, 2])
>>> np.isfinite(x, y)
array([0, 1, 0])
>>> y
array([0, 1, 0])
numpy.isfortran
Python Library Documentation: function isfortran in module numpy
isfortran(a)
Check if the array is Fortran contiguous but *not* C contiguous.
This function is obsolete. If you only want to check if an array is Fortran
contiguous use ``a.flags.f_contiguous`` instead.
Parameters
----------
a : ndarray
Input array.
Returns
-------
isfortran : bool
Returns True if the array is Fortran contiguous but *not* C contiguous.
Examples
--------
np.array allows to specify whether the array is written in C-contiguous
order (last index varies the fastest), or FORTRAN-contiguous order in
memory (first index varies the fastest).
>>> import numpy as np
>>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> np.isfortran(a)
False
>>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F')
>>> b
array([[1, 2, 3],
[4, 5, 6]])
>>> np.isfortran(b)
True
The transpose of a C-ordered array is a FORTRAN-ordered array.
>>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C')
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> np.isfortran(a)
False
>>> b = a.T
>>> b
array([[1, 4],
[2, 5],
[3, 6]])
>>> np.isfortran(b)
True
C-ordered arrays evaluate as False even if they are also FORTRAN-ordered.
>>> np.isfortran(np.array([1, 2], order='F'))
False
numpy.isin
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
isin(element, test_elements, assume_unique=False, invert=False, *, kind=None)
Calculates ``element in test_elements``, broadcasting over `element` only.
Returns a boolean array of the same shape as `element` that is True
where an element of `element` is in `test_elements` and False otherwise.
Parameters
----------
element : array_like
Input array.
test_elements : array_like
The values against which to test each value of `element`.
This argument is flattened if it is an array or array_like.
See notes for behavior with non-array-like parameters.
assume_unique : bool, optional
If True, the input arrays are both assumed to be unique, which
can speed up the calculation. Default is False.
invert : bool, optional
If True, the values in the returned array are inverted, as if
calculating `element not in test_elements`. Default is False.
``np.isin(a, b, invert=True)`` is equivalent to (but faster
than) ``np.invert(np.isin(a, b))``.
kind : {None, 'sort', 'table'}, optional
The algorithm to use. This will not affect the final result,
but will affect the speed and memory use. The default, None,
will select automatically based on memory considerations.
* If 'sort', will use a mergesort-based approach. This will have
a memory usage of roughly 6 times the sum of the sizes of
`element` and `test_elements`, not accounting for size of dtypes.
* If 'table', will use a lookup table approach similar
to a counting sort. This is only available for boolean and
integer arrays. This will have a memory usage of the
size of `element` plus the max-min value of `test_elements`.
`assume_unique` has no effect when the 'table' option is used.
* If None, will automatically choose 'table' if
the required memory allocation is less than or equal to
6 times the sum of the sizes of `element` and `test_elements`,
otherwise will use 'sort'. This is done to not use
a large amount of memory by default, even though
'table' may be faster in most cases. If 'table' is chosen,
`assume_unique` will have no effect.
Returns
-------
isin : ndarray, bool
Has the same shape as `element`. The values `element[isin]`
are in `test_elements`.
Notes
-----
`isin` is an element-wise function version of the python keyword `in`.
``isin(a, b)`` is roughly equivalent to
``np.array([item in b for item in a])`` if `a` and `b` are 1-D sequences.
`element` and `test_elements` are converted to arrays if they are not
already. If `test_elements` is a set (or other non-sequence collection)
it will be converted to an object array with one element, rather than an
array of the values contained in `test_elements`. This is a consequence
of the `array` constructor's way of handling non-sequence collections.
Converting the set to a list usually gives the desired behavior.
Using ``kind='table'`` tends to be faster than `kind='sort'` if the
following relationship is true:
``log10(len(test_elements)) >
(log10(max(test_elements)-min(test_elements)) - 2.27) / 0.927``,
but may use greater memory. The default value for `kind` will
be automatically selected based only on memory usage, so one may
manually set ``kind='table'`` if memory constraints can be relaxed.
.. versionadded:: 1.13.0
Examples
--------
>>> import numpy as np
>>> element = 2*np.arange(4).reshape((2, 2))
>>> element
array([[0, 2],
[4, 6]])
>>> test_elements = [1, 2, 4, 8]
>>> mask = np.isin(element, test_elements)
>>> mask
array([[False, True],
[ True, False]])
>>> element[mask]
array([2, 4])
The indices of the matched values can be obtained with `nonzero`:
>>> np.nonzero(mask)
(array([0, 1]), array([1, 0]))
The test can also be inverted:
>>> mask = np.isin(element, test_elements, invert=True)
>>> mask
array([[ True, False],
[False, True]])
>>> element[mask]
array([0, 6])
Because of how `array` handles sets, the following does not
work as expected:
>>> test_set = {1, 2, 4, 8}
>>> np.isin(element, test_set)
array([[False, False],
[False, False]])
Casting the set to a list gives the expected result:
>>> np.isin(element, list(test_set))
array([[False, True],
[ True, False]])
numpy.isinf
Python Library Documentation: ufunc
isinf = <ufunc 'isinf'>
isinf(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Test element-wise for positive or negative infinity.
Returns a boolean array of the same shape as `x`, True where ``x ==
+/-inf``, otherwise False.
Parameters
----------
x : array_like
Input values
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : bool (scalar) or boolean ndarray
True where ``x`` is positive or negative infinity, false otherwise.
This is a scalar if `x` is a scalar.
See Also
--------
isneginf, isposinf, isnan, isfinite
Notes
-----
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754).
Errors result if the second argument is supplied when the first
argument is a scalar, or if the first and second arguments have
different shapes.
Examples
--------
>>> import numpy as np
>>> np.isinf(np.inf)
True
>>> np.isinf(np.nan)
False
>>> np.isinf(-np.inf)
True
>>> np.isinf([np.inf, -np.inf, 1.0, np.nan])
array([ True, True, False, False])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([2, 2, 2])
>>> np.isinf(x, y)
array([1, 0, 1])
>>> y
array([1, 0, 1])
numpy.isnan
Python Library Documentation: ufunc
isnan = <ufunc 'isnan'>
isnan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Test element-wise for NaN and return result as a boolean array.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or bool
True where ``x`` is NaN, false otherwise.
This is a scalar if `x` is a scalar.
See Also
--------
isinf, isneginf, isposinf, isfinite, isnat
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.
Examples
--------
>>> import numpy as np
>>> np.isnan(np.nan)
True
>>> np.isnan(np.inf)
False
>>> np.isnan([np.log(-1.),1.,np.log(0)])
array([ True, False, False])
numpy.isnat
Python Library Documentation: ufunc
isnat = <ufunc 'isnat'>
isnat(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Test element-wise for NaT (not a time) and return result as a boolean array.
.. versionadded:: 1.13.0
Parameters
----------
x : array_like
Input array with datetime or timedelta data type.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or bool
True where ``x`` is NaT, false otherwise.
This is a scalar if `x` is a scalar.
See Also
--------
isnan, isinf, isneginf, isposinf, isfinite
Examples
--------
>>> import numpy as np
>>> np.isnat(np.datetime64("NaT"))
True
>>> np.isnat(np.datetime64("2016-01-01"))
False
>>> np.isnat(np.array(["NaT", "2016-01-01"], dtype="datetime64[ns]"))
array([ True, False])
numpy.isneginf
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
isneginf(x, out=None)
Test element-wise for negative infinity, return result as bool array.
Parameters
----------
x : array_like
The input array.
out : array_like, optional
A location into which the result is stored. If provided, it must have a
shape that the input broadcasts to. If not provided or None, a
freshly-allocated boolean array is returned.
Returns
-------
out : ndarray
A boolean array with the same dimensions as the input.
If second argument is not supplied then a numpy boolean array is
returned with values True where the corresponding element of the
input is negative infinity and values False where the element of
the input is not negative infinity.
If a second argument is supplied the result is stored there. If the
type of that array is a numeric type the result is represented as
zeros and ones, if the type is boolean then as False and True. The
return value `out` is then a reference to that array.
See Also
--------
isinf, isposinf, isnan, isfinite
Notes
-----
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754).
Errors result if the second argument is also supplied when x is a scalar
input, if first and second arguments have different shapes, or if the
first argument has complex values.
Examples
--------
>>> import numpy as np
>>> np.isneginf(-np.inf)
True
>>> np.isneginf(np.inf)
False
>>> np.isneginf([-np.inf, 0., np.inf])
array([ True, False, False])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([2, 2, 2])
>>> np.isneginf(x, y)
array([1, 0, 0])
>>> y
array([1, 0, 0])
numpy.isposinf
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
isposinf(x, out=None)
Test element-wise for positive infinity, return result as bool array.
Parameters
----------
x : array_like
The input array.
out : array_like, optional
A location into which the result is stored. If provided, it must have a
shape that the input broadcasts to. If not provided or None, a
freshly-allocated boolean array is returned.
Returns
-------
out : ndarray
A boolean array with the same dimensions as the input.
If second argument is not supplied then a boolean array is returned
with values True where the corresponding element of the input is
positive infinity and values False where the element of the input is
not positive infinity.
If a second argument is supplied the result is stored there. If the
type of that array is a numeric type the result is represented as zeros
and ones, if the type is boolean then as False and True.
The return value `out` is then a reference to that array.
See Also
--------
isinf, isneginf, isfinite, isnan
Notes
-----
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754).
Errors result if the second argument is also supplied when x is a scalar
input, if first and second arguments have different shapes, or if the
first argument has complex values
Examples
--------
>>> import numpy as np
>>> np.isposinf(np.inf)
True
>>> np.isposinf(-np.inf)
False
>>> np.isposinf([-np.inf, 0., np.inf])
array([False, False, True])
>>> x = np.array([-np.inf, 0., np.inf])
>>> y = np.array([2, 2, 2])
>>> np.isposinf(x, y)
array([0, 0, 1])
>>> y
array([0, 0, 1])
numpy.isreal
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
isreal(x)
Returns a bool array, where True if input element is real.
If element has complex type with zero imaginary part, the return value
for that element is True.
Parameters
----------
x : array_like
Input array.
Returns
-------
out : ndarray, bool
Boolean array of same shape as `x`.
Notes
-----
`isreal` may behave unexpectedly for string or object arrays (see examples)
See Also
--------
iscomplex
isrealobj : Return True if x is not a complex type.
Examples
--------
>>> import numpy as np
>>> a = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j], dtype=complex)
>>> np.isreal(a)
array([False, True, True, True, True, False])
The function does not work on string arrays.
>>> a = np.array([2j, "a"], dtype="U")
>>> np.isreal(a) # Warns about non-elementwise comparison
False
Returns True for all elements in input array of ``dtype=object`` even if
any of the elements is complex.
>>> a = np.array([1, "2", 3+4j], dtype=object)
>>> np.isreal(a)
array([ True, True, True])
isreal should not be used with object arrays
>>> a = np.array([1+2j, 2+1j], dtype=object)
>>> np.isreal(a)
array([ True, True])
numpy.isrealobj
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
isrealobj(x)
Return True if x is a not complex type or an array of complex numbers.
The type of the input is checked, not the value. So even if the input
has an imaginary part equal to zero, `isrealobj` evaluates to False
if the data type is complex.
Parameters
----------
x : any
The input can be of any type and shape.
Returns
-------
y : bool
The return value, False if `x` is of a complex type.
See Also
--------
iscomplexobj, isreal
Notes
-----
The function is only meant for arrays with numerical values but it
accepts all other objects. Since it assumes array input, the return
value of other objects may be True.
>>> np.isrealobj('A string')
True
>>> np.isrealobj(False)
True
>>> np.isrealobj(None)
True
Examples
--------
>>> import numpy as np
>>> np.isrealobj(1)
True
>>> np.isrealobj(1+0j)
False
>>> np.isrealobj([3, 1+0j, True])
False
numpy.isscalar
Python Library Documentation: function isscalar in module numpy
isscalar(element)
Returns True if the type of `element` is a scalar type.
Parameters
----------
element : any
Input argument, can be of any type and shape.
Returns
-------
val : bool
True if `element` is a scalar type, False if it is not.
See Also
--------
ndim : Get the number of dimensions of an array
Notes
-----
If you need a stricter way to identify a *numerical* scalar, use
``isinstance(x, numbers.Number)``, as that returns ``False`` for most
non-numerical elements such as strings.
In most cases ``np.ndim(x) == 0`` should be used instead of this function,
as that will also return true for 0d arrays. This is how numpy overloads
functions in the style of the ``dx`` arguments to `gradient` and
the ``bins`` argument to `histogram`. Some key differences:
+------------------------------------+---------------+-------------------+
| x |``isscalar(x)``|``np.ndim(x) == 0``|
+====================================+===============+===================+
| PEP 3141 numeric objects | ``True`` | ``True`` |
| (including builtins) | | |
+------------------------------------+---------------+-------------------+
| builtin string and buffer objects | ``True`` | ``True`` |
+------------------------------------+---------------+-------------------+
| other builtin objects, like | ``False`` | ``True`` |
| `pathlib.Path`, `Exception`, | | |
| the result of `re.compile` | | |
+------------------------------------+---------------+-------------------+
| third-party objects like | ``False`` | ``True`` |
| `matplotlib.figure.Figure` | | |
+------------------------------------+---------------+-------------------+
| zero-dimensional numpy arrays | ``False`` | ``True`` |
+------------------------------------+---------------+-------------------+
| other numpy arrays | ``False`` | ``False`` |
+------------------------------------+---------------+-------------------+
| `list`, `tuple`, and other | ``False`` | ``False`` |
| sequence objects | | |
+------------------------------------+---------------+-------------------+
Examples
--------
>>> import numpy as np
>>> np.isscalar(3.1)
True
>>> np.isscalar(np.array(3.1))
False
>>> np.isscalar([3.1])
False
>>> np.isscalar(False)
True
>>> np.isscalar('numpy')
True
NumPy supports PEP 3141 numbers:
>>> from fractions import Fraction
>>> np.isscalar(Fraction(5, 17))
True
>>> from numbers import Number
>>> np.isscalar(Number())
True
numpy.issubdtype
Python Library Documentation: function issubdtype in module numpy
issubdtype(arg1, arg2)
Returns True if first argument is a typecode lower/equal in type hierarchy.
This is like the builtin :func:`issubclass`, but for `dtype`\ s.
Parameters
----------
arg1, arg2 : dtype_like
`dtype` or object coercible to one
Returns
-------
out : bool
See Also
--------
:ref:`arrays.scalars` : Overview of the numpy type hierarchy.
Examples
--------
`issubdtype` can be used to check the type of arrays:
>>> ints = np.array([1, 2, 3], dtype=np.int32)
>>> np.issubdtype(ints.dtype, np.integer)
True
>>> np.issubdtype(ints.dtype, np.floating)
False
>>> floats = np.array([1, 2, 3], dtype=np.float32)
>>> np.issubdtype(floats.dtype, np.integer)
False
>>> np.issubdtype(floats.dtype, np.floating)
True
Similar types of different sizes are not subdtypes of each other:
>>> np.issubdtype(np.float64, np.float32)
False
>>> np.issubdtype(np.float32, np.float64)
False
but both are subtypes of `floating`:
>>> np.issubdtype(np.float64, np.floating)
True
>>> np.issubdtype(np.float32, np.floating)
True
For convenience, dtype-like objects are allowed too:
>>> np.issubdtype('S1', np.bytes_)
True
>>> np.issubdtype('i4', np.signedinteger)
True
numpy.iterable
Python Library Documentation: function iterable in module numpy
iterable(y)
Check whether or not an object can be iterated over.
Parameters
----------
y : object
Input object.
Returns
-------
b : bool
Return ``True`` if the object has an iterator method or is a
sequence and ``False`` otherwise.
Examples
--------
>>> import numpy as np
>>> np.iterable([1, 2, 3])
True
>>> np.iterable(2)
False
Notes
-----
In most cases, the results of ``np.iterable(obj)`` are consistent with
``isinstance(obj, collections.abc.Iterable)``. One notable exception is
the treatment of 0-dimensional arrays::
>>> from collections.abc import Iterable
>>> a = np.array(1.0) # 0-dimensional numpy array
>>> isinstance(a, Iterable)
True
>>> np.iterable(a)
False
numpy.ix_
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
ix_(*args)
Construct an open mesh from multiple sequences.
This function takes N 1-D sequences and returns N outputs with N
dimensions each, such that the shape is 1 in all but one dimension
and the dimension with the non-unit shape value cycles through all
N dimensions.
Using `ix_` one can quickly construct index arrays that will index
the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array
``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.
Parameters
----------
args : 1-D sequences
Each sequence should be of integer or boolean type.
Boolean sequences will be interpreted as boolean masks for the
corresponding dimension (equivalent to passing in
``np.nonzero(boolean_sequence)``).
Returns
-------
out : tuple of ndarrays
N arrays with N dimensions each, with N the number of input
sequences. Together these arrays form an open mesh.
See Also
--------
ogrid, mgrid, meshgrid
Examples
--------
>>> import numpy as np
>>> a = np.arange(10).reshape(2, 5)
>>> a
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> ixgrid = np.ix_([0, 1], [2, 4])
>>> ixgrid
(array([[0],
[1]]), array([[2, 4]]))
>>> ixgrid[0].shape, ixgrid[1].shape
((2, 1), (1, 2))
>>> a[ixgrid]
array([[2, 4],
[7, 9]])
>>> ixgrid = np.ix_([True, True], [2, 4])
>>> a[ixgrid]
array([[2, 4],
[7, 9]])
>>> ixgrid = np.ix_([True, True], [False, False, True, False, True])
>>> a[ixgrid]
array([[2, 4],
[7, 9]])
numpy.kaiser
Python Library Documentation: function kaiser in module numpy
kaiser(M, beta)
Return the Kaiser window.
The Kaiser window is a taper formed by using a Bessel function.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
beta : float
Shape parameter for window.
Returns
-------
out : array
The window, with the maximum value normalized to one (the value
one appears only if the number of samples is odd).
See Also
--------
bartlett, blackman, hamming, hanning
Notes
-----
The Kaiser window is defined as
.. math:: w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}}
\right)/I_0(\beta)
with
.. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2},
where :math:`I_0` is the modified zeroth-order Bessel function.
The Kaiser was named for Jim Kaiser, who discovered a simple
approximation to the DPSS window based on Bessel functions. The Kaiser
window is a very good approximation to the Digital Prolate Spheroidal
Sequence, or Slepian window, which is the transform which maximizes the
energy in the main lobe of the window relative to total energy.
The Kaiser can approximate many other windows by varying the beta
parameter.
==== =======================
beta Window shape
==== =======================
0 Rectangular
5 Similar to a Hamming
6 Similar to a Hanning
8.6 Similar to a Blackman
==== =======================
A beta value of 14 is probably a good starting point. Note that as beta
gets large, the window narrows, and so the number of samples needs to be
large enough to sample the increasingly narrow spike, otherwise NaNs will
get returned.
Most references to the Kaiser window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by
digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285.
John Wiley and Sons, New York, (1966).
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 177-178.
.. [3] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> np.kaiser(12, 14)
array([7.72686684e-06, 3.46009194e-03, 4.65200189e-02, # may vary
2.29737120e-01, 5.99885316e-01, 9.45674898e-01,
9.45674898e-01, 5.99885316e-01, 2.29737120e-01,
4.65200189e-02, 3.46009194e-03, 7.72686684e-06])
Plot the window and the frequency response.
.. plot::
:include-source:
import matplotlib.pyplot as plt
from numpy.fft import fft, fftshift
window = np.kaiser(51, 14)
plt.plot(window)
plt.title("Kaiser window")
plt.ylabel("Amplitude")
plt.xlabel("Sample")
plt.show()
plt.figure()
A = fft(window, 2048) / 25.5
mag = np.abs(fftshift(A))
freq = np.linspace(-0.5, 0.5, len(A))
response = 20 * np.log10(mag)
response = np.clip(response, -100, 100)
plt.plot(freq, response)
plt.title("Frequency response of Kaiser window")
plt.ylabel("Magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
plt.axis('tight')
plt.show()
numpy.kron
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
kron(a, b)
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the
second array scaled by the first.
Parameters
----------
a, b : array_like
Returns
-------
out : ndarray
See Also
--------
outer : The outer product
Notes
-----
The function assumes that the number of dimensions of `a` and `b`
are the same, if necessary prepending the smallest with ones.
If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``,
the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``.
The elements are products of elements from `a` and `b`, organized
explicitly by::
kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
where::
kt = it * st + jt, t = 0,...,N
In the common 2-D case (N=1), the block structure can be visualized::
[[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ],
[ ... ... ],
[ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]]
Examples
--------
>>> import numpy as np
>>> np.kron([1,10,100], [5,6,7])
array([ 5, 6, 7, ..., 500, 600, 700])
>>> np.kron([5,6,7], [1,10,100])
array([ 5, 50, 500, ..., 7, 70, 700])
>>> np.kron(np.eye(2), np.ones((2,2)))
array([[1., 1., 0., 0.],
[1., 1., 0., 0.],
[0., 0., 1., 1.],
[0., 0., 1., 1.]])
>>> a = np.arange(100).reshape((2,5,2,5))
>>> b = np.arange(24).reshape((2,3,4))
>>> c = np.kron(a,b)
>>> c.shape
(2, 10, 6, 20)
>>> I = (1,3,0,2)
>>> J = (0,2,1)
>>> J1 = (0,) + J # extend to ndim=4
>>> S1 = (1,) + b.shape
>>> K = tuple(np.array(I) * np.array(S1) + np.array(J1))
>>> c[K] == a[I]*b[J]
True
numpy.lcm
Python Library Documentation: ufunc
lcm = <ufunc 'lcm'>
lcm(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns the lowest common multiple of ``|x1|`` and ``|x2|``
Parameters
----------
x1, x2 : array_like, int
Arrays of values.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
Returns
-------
y : ndarray or scalar
The lowest common multiple of the absolute value of the inputs
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
gcd : The greatest common divisor
Examples
--------
>>> import numpy as np
>>> np.lcm(12, 20)
60
>>> np.lcm.reduce([3, 12, 20])
60
>>> np.lcm.reduce([40, 12, 20])
120
>>> np.lcm(np.arange(6), 20)
array([ 0, 20, 20, 60, 20, 20])
numpy.ldexp
Python Library Documentation: ufunc
ldexp = <ufunc 'ldexp'>
ldexp(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns x1 * 2**x2, element-wise.
The mantissas `x1` and twos exponents `x2` are used to construct
floating point numbers ``x1 * 2**x2``.
Parameters
----------
x1 : array_like
Array of multipliers.
x2 : array_like, int
Array of twos exponents.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The result of ``x1 * 2**x2``.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
frexp : Return (y1, y2) from ``x = y1 * 2**y2``, inverse to `ldexp`.
Notes
-----
Complex dtypes are not supported, they will raise a TypeError.
`ldexp` is useful as the inverse of `frexp`, if used by itself it is
more clear to simply use the expression ``x1 * 2**x2``.
Examples
--------
>>> import numpy as np
>>> np.ldexp(5, np.arange(4))
array([ 5., 10., 20., 40.], dtype=float16)
>>> x = np.arange(6)
>>> np.ldexp(*np.frexp(x))
array([ 0., 1., 2., 3., 4., 5.])
numpy.left_shift
Python Library Documentation: ufunc
left_shift = <ufunc 'left_shift'>
left_shift(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Shift the bits of an integer to the left.
Bits are shifted to the left by appending `x2` 0s at the right of `x1`.
Since the internal representation of numbers is in binary format, this
operation is equivalent to multiplying `x1` by ``2**x2``.
Parameters
----------
x1 : array_like of integer type
Input values.
x2 : array_like of integer type
Number of zeros to append to `x1`. Has to be non-negative.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : array of integer type
Return `x1` with bits shifted `x2` times to the left.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
right_shift : Shift the bits of an integer to the right.
binary_repr : Return the binary representation of the input number
as a string.
Examples
--------
>>> import numpy as np
>>> np.binary_repr(5)
'101'
>>> np.left_shift(5, 2)
20
>>> np.binary_repr(20)
'10100'
>>> np.left_shift(5, [1,2,3])
array([10, 20, 40])
Note that the dtype of the second argument may change the dtype of the
result and can lead to unexpected results in some cases (see
:ref:`Casting Rules <ufuncs.casting>`):
>>> a = np.left_shift(np.uint8(255), np.int64(1)) # Expect 254
>>> print(a, type(a)) # Unexpected result due to upcasting
510 <class 'numpy.int64'>
>>> b = np.left_shift(np.uint8(255), np.uint8(1))
>>> print(b, type(b))
254 <class 'numpy.uint8'>
The ``<<`` operator can be used as a shorthand for ``np.left_shift`` on
ndarrays.
>>> x1 = 5
>>> x2 = np.array([1, 2, 3])
>>> x1 << x2
array([10, 20, 40])
numpy.less
Python Library Documentation: ufunc
less = <ufunc 'less'>
less(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 < x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
greater, less_equal, greater_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.less([1, 2], [2, 2])
array([ True, False])
The ``<`` operator can be used as a shorthand for ``np.less`` on ndarrays.
>>> a = np.array([1, 2])
>>> b = np.array([2, 2])
>>> a < b
array([ True, False])
numpy.less_equal
Python Library Documentation: ufunc
less_equal = <ufunc 'less_equal'>
less_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 <= x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
greater, less, greater_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.less_equal([4, 2, 1], [2, 2, 2])
array([False, True, True])
The ``<=`` operator can be used as a shorthand for ``np.less_equal`` on
ndarrays.
>>> a = np.array([4, 2, 1])
>>> b = np.array([2, 2, 2])
>>> a <= b
array([False, True, True])
numpy.lexsort
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
lexsort(...)
lexsort(keys, axis=-1)
Perform an indirect stable sort using a sequence of keys.
Given multiple sorting keys, lexsort returns an array of integer indices
that describes the sort order by multiple keys. The last key in the
sequence is used for the primary sort order, ties are broken by the
second-to-last key, and so on.
Parameters
----------
keys : (k, m, n, ...) array-like
The `k` keys to be sorted. The *last* key (e.g, the last
row if `keys` is a 2D array) is the primary sort key.
Each element of `keys` along the zeroth axis must be
an array-like object of the same shape.
axis : int, optional
Axis to be indirectly sorted. By default, sort over the last axis
of each sequence. Separate slices along `axis` sorted over
independently; see last example.
Returns
-------
indices : (m, n, ...) ndarray of ints
Array of indices that sort the keys along the specified axis.
See Also
--------
argsort : Indirect sort.
ndarray.sort : In-place sort.
sort : Return a sorted copy of an array.
Examples
--------
Sort names: first by surname, then by name.
>>> import numpy as np
>>> surnames = ('Hertz', 'Galilei', 'Hertz')
>>> first_names = ('Heinrich', 'Galileo', 'Gustav')
>>> ind = np.lexsort((first_names, surnames))
>>> ind
array([1, 2, 0])
>>> [surnames[i] + ", " + first_names[i] for i in ind]
['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']
Sort according to two numerical keys, first by elements
of ``a``, then breaking ties according to elements of ``b``:
>>> a = [1, 5, 1, 4, 3, 4, 4] # First sequence
>>> b = [9, 4, 0, 4, 0, 2, 1] # Second sequence
>>> ind = np.lexsort((b, a)) # Sort by `a`, then by `b`
>>> ind
array([2, 0, 4, 6, 5, 3, 1])
>>> [(a[i], b[i]) for i in ind]
[(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]
Compare against `argsort`, which would sort each key independently.
>>> np.argsort((b, a), kind='stable')
array([[2, 4, 6, 5, 1, 3, 0],
[0, 2, 4, 3, 5, 6, 1]])
To sort lexicographically with `argsort`, we would need to provide a
structured array.
>>> x = np.array([(ai, bi) for ai, bi in zip(a, b)],
... dtype = np.dtype([('x', int), ('y', int)]))
>>> np.argsort(x) # or np.argsort(x, order=('x', 'y'))
array([2, 0, 4, 6, 5, 3, 1])
The zeroth axis of `keys` always corresponds with the sequence of keys,
so 2D arrays are treated just like other sequences of keys.
>>> arr = np.asarray([b, a])
>>> ind2 = np.lexsort(arr)
>>> np.testing.assert_equal(ind2, ind)
Accordingly, the `axis` parameter refers to an axis of *each* key, not of
the `keys` argument itself. For instance, the array ``arr`` is treated as
a sequence of two 1-D keys, so specifying ``axis=0`` is equivalent to
using the default axis, ``axis=-1``.
>>> np.testing.assert_equal(np.lexsort(arr, axis=0),
... np.lexsort(arr, axis=-1))
For higher-dimensional arrays, the axis parameter begins to matter. The
resulting array has the same shape as each key, and the values are what
we would expect if `lexsort` were performed on corresponding slices
of the keys independently. For instance,
>>> x = [[1, 2, 3, 4],
... [4, 3, 2, 1],
... [2, 1, 4, 3]]
>>> y = [[2, 2, 1, 1],
... [1, 2, 1, 2],
... [1, 1, 2, 1]]
>>> np.lexsort((x, y), axis=1)
array([[2, 3, 0, 1],
[2, 0, 3, 1],
[1, 0, 3, 2]])
Each row of the result is what we would expect if we were to perform
`lexsort` on the corresponding row of the keys:
>>> for i in range(3):
... print(np.lexsort((x[i], y[i])))
[2 3 0 1]
[2 0 3 1]
[1 0 3 2]
numpy.lib
Python Library Documentation: package numpy.lib in numpy
NAME
numpy.lib
DESCRIPTION
``numpy.lib`` is mostly a space for implementing functions that don't
belong in core or in another NumPy submodule with a clear purpose
(e.g. ``random``, ``fft``, ``linalg``, ``ma``).
``numpy.lib``'s private submodules contain basic functions that are used by
other public modules and are useful to have in the main name-space.
PACKAGE CONTENTS
_array_utils_impl
_arraypad_impl
_arraysetops_impl
_arrayterator_impl
_datasource
_function_base_impl
_histograms_impl
_index_tricks_impl
_iotools
_nanfunctions_impl
_npyio_impl
_polynomial_impl
_scimath_impl
_shape_base_impl
_stride_tricks_impl
_twodim_base_impl
_type_check_impl
_ufunclike_impl
_user_array_impl
_utils_impl
_version
array_utils
format
introspect
mixins
npyio
recfunctions
scimath
stride_tricks
tests (package)
user_array
CLASSES
builtins.object
numpy.lib._arrayterator_impl.Arrayterator
numpy.lib._version.NumpyVersion
class Arrayterator(builtins.object)
| Arrayterator(var, buf_size=None)
|
| Buffered iterator for big arrays.
|
| `Arrayterator` creates a buffered iterator for reading big arrays in small
| contiguous blocks. The class is useful for objects stored in the
| file system. It allows iteration over the object *without* reading
| everything in memory; instead, small blocks are read and iterated over.
|
| `Arrayterator` can be used with any object that supports multidimensional
| slices. This includes NumPy arrays, but also variables from
| Scientific.IO.NetCDF or pynetcdf for example.
|
| Parameters
| ----------
| var : array_like
| The object to iterate over.
| buf_size : int, optional
| The buffer size. If `buf_size` is supplied, the maximum amount of
| data that will be read into memory is `buf_size` elements.
| Default is None, which will read as many element as possible
| into memory.
|
| Attributes
| ----------
| var
| buf_size
| start
| stop
| step
| shape
| flat
|
| See Also
| --------
| numpy.ndenumerate : Multidimensional array iterator.
| numpy.flatiter : Flat array iterator.
| numpy.memmap : Create a memory-map to an array stored
| in a binary file on disk.
|
| Notes
| -----
| The algorithm works by first finding a "running dimension", along which
| the blocks will be extracted. Given an array of dimensions
| ``(d1, d2, ..., dn)``, e.g. if `buf_size` is smaller than ``d1``, the
| first dimension will be used. If, on the other hand,
| ``d1 < buf_size < d1*d2`` the second dimension will be used, and so on.
| Blocks are extracted along this dimension, and when the last block is
| returned the process continues from the next dimension, until all
| elements have been read.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6)
| >>> a_itor = np.lib.Arrayterator(a, 2)
| >>> a_itor.shape
| (3, 4, 5, 6)
|
| Now we can iterate over ``a_itor``, and it will return arrays of size
| two. Since `buf_size` was smaller than any dimension, the first
| dimension will be iterated over first:
|
| >>> for subarr in a_itor:
| ... if not subarr.all():
| ... print(subarr, subarr.shape) # doctest: +SKIP
| >>> # [[[[0 1]]]] (1, 1, 1, 2)
|
| Methods defined here:
|
| __array__(self, dtype=None, copy=None)
| Return corresponding data.
|
| __getattr__(self, attr)
|
| __getitem__(self, index)
| Return a new arrayterator.
|
| __init__(self, var, buf_size=None)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self)
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| flat
| A 1-D flat iterator for Arrayterator objects.
|
| This iterator returns elements of the array to be iterated over in
| `~lib.Arrayterator` one by one.
| It is similar to `flatiter`.
|
| See Also
| --------
| lib.Arrayterator
| flatiter
|
| Examples
| --------
| >>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6)
| >>> a_itor = np.lib.Arrayterator(a, 2)
|
| >>> for subarr in a_itor.flat:
| ... if not subarr:
| ... print(subarr, type(subarr))
| ...
| 0 <class 'numpy.int64'>
|
| shape
| The shape of the array to be iterated over.
|
| For an example, see `Arrayterator`.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class NumpyVersion(builtins.object)
| NumpyVersion(vstring)
|
| Parse and compare numpy version strings.
|
| NumPy has the following versioning scheme (numbers given are examples; they
| can be > 9 in principle):
|
| - Released version: '1.8.0', '1.8.1', etc.
| - Alpha: '1.8.0a1', '1.8.0a2', etc.
| - Beta: '1.8.0b1', '1.8.0b2', etc.
| - Release candidates: '1.8.0rc1', '1.8.0rc2', etc.
| - Development versions: '1.8.0.dev-f1234afa' (git commit hash appended)
| - Development versions after a1: '1.8.0a1.dev-f1234afa',
| '1.8.0b2.dev-f1234afa',
| '1.8.1rc1.dev-f1234afa', etc.
| - Development versions (no git hash available): '1.8.0.dev-Unknown'
|
| Comparing needs to be done against a valid version string or other
| `NumpyVersion` instance. Note that all development versions of the same
| (pre-)release compare equal.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| vstring : str
| NumPy version string (``np.__version__``).
|
| Examples
| --------
| >>> from numpy.lib import NumpyVersion
| >>> if NumpyVersion(np.__version__) < '1.7.0':
| ... print('skip')
| >>> # skip
|
| >>> NumpyVersion('1.7') # raises ValueError, add ".0"
| Traceback (most recent call last):
| ...
| ValueError: Not a valid numpy version string
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __ge__(self, other)
| Return self>=value.
|
| __gt__(self, other)
| Return self>value.
|
| __init__(self, vstring)
| Initialize self. See help(type(self)) for accurate signature.
|
| __le__(self, other)
| Return self<=value.
|
| __lt__(self, other)
| Return self<value.
|
| __ne__(self, other)
| Return self!=value.
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
FUNCTIONS
__getattr__(attr)
add_docstring(...)
add_docstring(obj, docstring)
Add a docstring to a built-in obj if possible.
If the obj already has a docstring raise a RuntimeError
If this routine does not know how to add a docstring to the object
raise a TypeError
add_newdoc(place, obj, doc, warn_on_python=True)
Add documentation to an existing object, typically one defined in C
The purpose is to allow easier editing of the docstrings without requiring
a re-compile. This exists primarily for internal use within numpy itself.
Parameters
----------
place : str
The absolute name of the module to import from
obj : str or None
The name of the object to add documentation to, typically a class or
function name.
doc : {str, Tuple[str, str], List[Tuple[str, str]]}
If a string, the documentation to apply to `obj`
If a tuple, then the first element is interpreted as an attribute
of `obj` and the second as the docstring to apply -
``(method, docstring)``
If a list, then each element of the list should be a tuple of length
two - ``[(method1, docstring1), (method2, docstring2), ...]``
warn_on_python : bool
If True, the default, emit `UserWarning` if this is used to attach
documentation to a pure-python object.
Notes
-----
This routine never raises an error if the docstring can't be written, but
will raise an error if the object being documented does not exist.
This routine cannot modify read-only docstrings, as appear
in new-style classes or built-in functions. Because this
routine never raises an error the caller must check manually
that the docstrings were changed.
Since this function grabs the ``char *`` from a c-level str object and puts
it into the ``tp_doc`` slot of the type of `obj`, it violates a number of
C-API best-practices, by:
- modifying a `PyTypeObject` after calling `PyType_Ready`
- calling `Py_INCREF` on the str and losing the reference, so the str
will never be released
If possible it should be avoided.
DATA
__all__ = ['Arrayterator', 'add_docstring', 'add_newdoc', 'array_utils...
tracemalloc_domain = 389047
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\lib\__init__.py
numpy.linalg
Python Library Documentation: package numpy.linalg in numpy
NAME
numpy.linalg
DESCRIPTION
``numpy.linalg``
================
The NumPy linear algebra functions rely on BLAS and LAPACK to provide efficient
low level implementations of standard linear algebra algorithms. Those
libraries may be provided by NumPy itself using C versions of a subset of their
reference implementations but, when possible, highly optimized libraries that
take advantage of specialized processor functionality are preferred. Examples
of such libraries are OpenBLAS, MKL (TM), and ATLAS. Because those libraries
are multithreaded and processor dependent, environmental variables and external
packages such as threadpoolctl may be needed to control the number of threads
or specify the processor architecture.
- OpenBLAS: https://www.openblas.net/
- threadpoolctl: https://github.com/joblib/threadpoolctl
Please note that the most-used linear algebra functions in NumPy are present in
the main ``numpy`` namespace rather than in ``numpy.linalg``. There are:
``dot``, ``vdot``, ``inner``, ``outer``, ``matmul``, ``tensordot``, ``einsum``,
``einsum_path`` and ``kron``.
Functions present in numpy.linalg are listed below.
Matrix and vector products
--------------------------
cross
multi_dot
matrix_power
tensordot
matmul
Decompositions
--------------
cholesky
outer
qr
svd
svdvals
Matrix eigenvalues
------------------
eig
eigh
eigvals
eigvalsh
Norms and other numbers
-----------------------
norm
matrix_norm
vector_norm
cond
det
matrix_rank
slogdet
trace (Array API compatible)
Solving equations and inverting matrices
----------------------------------------
solve
tensorsolve
lstsq
inv
pinv
tensorinv
Other matrix operations
-----------------------
diagonal (Array API compatible)
matrix_transpose (Array API compatible)
Exceptions
----------
LinAlgError
PACKAGE CONTENTS
_linalg
_umath_linalg
lapack_lite
linalg
tests (package)
CLASSES
builtins.ValueError(builtins.Exception)
LinAlgError
class LinAlgError(builtins.ValueError)
| Generic Python-exception-derived object raised by linalg functions.
|
| General purpose exception class, derived from Python's ValueError
| class, programmatically raised in linalg functions when a Linear
| Algebra-related condition would prevent further correct execution of the
| function.
|
| Parameters
| ----------
| None
|
| Examples
| --------
| >>> from numpy import linalg as LA
| >>> LA.inv(np.zeros((2,2)))
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| File "...linalg.py", line 350,
| in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
| File "...linalg.py", line 249,
| in solve
| raise LinAlgError('Singular matrix')
| numpy.linalg.LinAlgError: Singular matrix
|
| Method resolution order:
| LinAlgError
| builtins.ValueError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.ValueError:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.ValueError:
|
| __new__(*args, **kwargs) class method of builtins.ValueError
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
FUNCTIONS
cholesky(a, /, *, upper=False)
Cholesky decomposition.
Return the lower or upper Cholesky decomposition, ``L * L.H`` or
``U.H * U``, of the square matrix ``a``, where ``L`` is lower-triangular,
``U`` is upper-triangular, and ``.H`` is the conjugate transpose operator
(which is the ordinary transpose if ``a`` is real-valued). ``a`` must be
Hermitian (symmetric if real-valued) and positive-definite. No checking is
performed to verify whether ``a`` is Hermitian or not. In addition, only
the lower or upper-triangular and diagonal elements of ``a`` are used.
Only ``L`` or ``U`` is actually returned.
Parameters
----------
a : (..., M, M) array_like
Hermitian (symmetric if all elements are real), positive-definite
input matrix.
upper : bool
If ``True``, the result must be the upper-triangular Cholesky factor.
If ``False``, the result must be the lower-triangular Cholesky factor.
Default: ``False``.
Returns
-------
L : (..., M, M) array_like
Lower or upper-triangular Cholesky factor of `a`. Returns a matrix
object if `a` is a matrix object.
Raises
------
LinAlgError
If the decomposition fails, for example, if `a` is not
positive-definite.
See Also
--------
scipy.linalg.cholesky : Similar function in SciPy.
scipy.linalg.cholesky_banded : Cholesky decompose a banded Hermitian
positive-definite matrix.
scipy.linalg.cho_factor : Cholesky decomposition of a matrix, to use in
`scipy.linalg.cho_solve`.
Notes
-----
.. versionadded:: 1.8.0
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
The Cholesky decomposition is often used as a fast way of solving
.. math:: A \mathbf{x} = \mathbf{b}
(when `A` is both Hermitian/symmetric and positive-definite).
First, we solve for :math:`\mathbf{y}` in
.. math:: L \mathbf{y} = \mathbf{b},
and then for :math:`\mathbf{x}` in
.. math:: L^{H} \mathbf{x} = \mathbf{y}.
Examples
--------
>>> import numpy as np
>>> A = np.array([[1,-2j],[2j,5]])
>>> A
array([[ 1.+0.j, -0.-2.j],
[ 0.+2.j, 5.+0.j]])
>>> L = np.linalg.cholesky(A)
>>> L
array([[1.+0.j, 0.+0.j],
[0.+2.j, 1.+0.j]])
>>> np.dot(L, L.T.conj()) # verify that L * L.H = A
array([[1.+0.j, 0.-2.j],
[0.+2.j, 5.+0.j]])
>>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like?
>>> np.linalg.cholesky(A) # an ndarray object is returned
array([[1.+0.j, 0.+0.j],
[0.+2.j, 1.+0.j]])
>>> # But a matrix object is returned if A is a matrix object
>>> np.linalg.cholesky(np.matrix(A))
matrix([[ 1.+0.j, 0.+0.j],
[ 0.+2.j, 1.+0.j]])
>>> # The upper-triangular Cholesky factor can also be obtained.
>>> np.linalg.cholesky(A, upper=True)
array([[1.-0.j, 0.-2.j],
[0.-0.j, 1.-0.j]])
cond(x, p=None)
Compute the condition number of a matrix.
This function is capable of returning the condition number using
one of seven different norms, depending on the value of `p` (see
Parameters below).
Parameters
----------
x : (..., M, N) array_like
The matrix whose condition number is sought.
p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional
Order of the norm used in the condition number computation:
===== ============================
p norm for matrices
===== ============================
None 2-norm, computed directly using the ``SVD``
'fro' Frobenius norm
inf max(sum(abs(x), axis=1))
-inf min(sum(abs(x), axis=1))
1 max(sum(abs(x), axis=0))
-1 min(sum(abs(x), axis=0))
2 2-norm (largest sing. value)
-2 smallest singular value
===== ============================
inf means the `numpy.inf` object, and the Frobenius norm is
the root-of-sum-of-squares norm.
Returns
-------
c : {float, inf}
The condition number of the matrix. May be infinite.
See Also
--------
numpy.linalg.norm
Notes
-----
The condition number of `x` is defined as the norm of `x` times the
norm of the inverse of `x` [1]_; the norm can be the usual L2-norm
(root-of-sum-of-squares) or one of a number of other matrix norms.
References
----------
.. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL,
Academic Press, Inc., 1980, pg. 285.
Examples
--------
>>> import numpy as np
>>> from numpy import linalg as LA
>>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
>>> a
array([[ 1, 0, -1],
[ 0, 1, 0],
[ 1, 0, 1]])
>>> LA.cond(a)
1.4142135623730951
>>> LA.cond(a, 'fro')
3.1622776601683795
>>> LA.cond(a, np.inf)
2.0
>>> LA.cond(a, -np.inf)
1.0
>>> LA.cond(a, 1)
2.0
>>> LA.cond(a, -1)
1.0
>>> LA.cond(a, 2)
1.4142135623730951
>>> LA.cond(a, -2)
0.70710678118654746 # may vary
>>> (min(LA.svd(a, compute_uv=False)) *
... min(LA.svd(LA.inv(a), compute_uv=False)))
0.70710678118654746 # may vary
cross(x1, x2, /, *, axis=-1)
Returns the cross product of 3-element vectors.
If ``x1`` and/or ``x2`` are multi-dimensional arrays, then
the cross-product of each pair of corresponding 3-element vectors
is independently computed.
This function is Array API compatible, contrary to
:func:`numpy.cross`.
Parameters
----------
x1 : array_like
The first input array.
x2 : array_like
The second input array. Must be compatible with ``x1`` for all
non-compute axes. The size of the axis over which to compute
the cross-product must be the same size as the respective axis
in ``x1``.
axis : int, optional
The axis (dimension) of ``x1`` and ``x2`` containing the vectors for
which to compute the cross-product. Default: ``-1``.
Returns
-------
out : ndarray
An array containing the cross products.
See Also
--------
numpy.cross
Examples
--------
Vector cross-product.
>>> x = np.array([1, 2, 3])
>>> y = np.array([4, 5, 6])
>>> np.linalg.cross(x, y)
array([-3, 6, -3])
Multiple vector cross-products. Note that the direction of the cross
product vector is defined by the *right-hand rule*.
>>> x = np.array([[1,2,3], [4,5,6]])
>>> y = np.array([[4,5,6], [1,2,3]])
>>> np.linalg.cross(x, y)
array([[-3, 6, -3],
[ 3, -6, 3]])
>>> x = np.array([[1, 2], [3, 4], [5, 6]])
>>> y = np.array([[4, 5], [6, 1], [2, 3]])
>>> np.linalg.cross(x, y, axis=0)
array([[-24, 6],
[ 18, 24],
[-6, -18]])
det(a)
Compute the determinant of an array.
Parameters
----------
a : (..., M, M) array_like
Input array to compute determinants for.
Returns
-------
det : (...) array_like
Determinant of `a`.
See Also
--------
slogdet : Another way to represent the determinant, more suitable
for large matrices where underflow/overflow may occur.
scipy.linalg.det : Similar function in SciPy.
Notes
-----
.. versionadded:: 1.8.0
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
The determinant is computed via LU factorization using the LAPACK
routine ``z/dgetrf``.
Examples
--------
The determinant of a 2-D array [[a, b], [c, d]] is ad - bc:
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> np.linalg.det(a)
-2.0 # may vary
Computing determinants for a stack of matrices:
>>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
>>> a.shape
(3, 2, 2)
>>> np.linalg.det(a)
array([-2., -3., -8.])
diagonal(x, /, *, offset=0)
Returns specified diagonals of a matrix (or a stack of matrices) ``x``.
This function is Array API compatible, contrary to
:py:func:`numpy.diagonal`, the matrix is assumed
to be defined by the last two dimensions.
Parameters
----------
x : (...,M,N) array_like
Input array having shape (..., M, N) and whose innermost two
dimensions form MxN matrices.
offset : int, optional
Offset specifying the off-diagonal relative to the main diagonal,
where::
* offset = 0: the main diagonal.
* offset > 0: off-diagonal above the main diagonal.
* offset < 0: off-diagonal below the main diagonal.
Returns
-------
out : (...,min(N,M)) ndarray
An array containing the diagonals and whose shape is determined by
removing the last two dimensions and appending a dimension equal to
the size of the resulting diagonals. The returned array must have
the same data type as ``x``.
See Also
--------
numpy.diagonal
Examples
--------
>>> a = np.arange(4).reshape(2, 2); a
array([[0, 1],
[2, 3]])
>>> np.linalg.diagonal(a)
array([0, 3])
A 3-D example:
>>> a = np.arange(8).reshape(2, 2, 2); a
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.linalg.diagonal(a)
array([[0, 3],
[4, 7]])
Diagonals adjacent to the main diagonal can be obtained by using the
`offset` argument:
>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.linalg.diagonal(a, offset=1) # First superdiagonal
array([1, 5])
>>> np.linalg.diagonal(a, offset=2) # Second superdiagonal
array([2])
>>> np.linalg.diagonal(a, offset=-1) # First subdiagonal
array([3, 7])
>>> np.linalg.diagonal(a, offset=-2) # Second subdiagonal
array([6])
The anti-diagonal can be obtained by reversing the order of elements
using either `numpy.flipud` or `numpy.fliplr`.
>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.linalg.diagonal(np.fliplr(a)) # Horizontal flip
array([2, 4, 6])
>>> np.linalg.diagonal(np.flipud(a)) # Vertical flip
array([6, 4, 2])
Note that the order in which the diagonal is retrieved varies depending
on the flip function.
eig(a)
Compute the eigenvalues and right eigenvectors of a square array.
Parameters
----------
a : (..., M, M) array
Matrices for which the eigenvalues and right eigenvectors will
be computed
Returns
-------
A namedtuple with the following attributes:
eigenvalues : (..., M) array
The eigenvalues, each repeated according to its multiplicity.
The eigenvalues are not necessarily ordered. The resulting
array will be of complex type, unless the imaginary part is
zero in which case it will be cast to a real type. When `a`
is real the resulting eigenvalues will be real (0 imaginary
part) or occur in conjugate pairs
eigenvectors : (..., M, M) array
The normalized (unit "length") eigenvectors, such that the
column ``eigenvectors[:,i]`` is the eigenvector corresponding to the
eigenvalue ``eigenvalues[i]``.
Raises
------
LinAlgError
If the eigenvalue computation does not converge.
See Also
--------
eigvals : eigenvalues of a non-symmetric array.
eigh : eigenvalues and eigenvectors of a real symmetric or complex
Hermitian (conjugate symmetric) array.
eigvalsh : eigenvalues of a real symmetric or complex Hermitian
(conjugate symmetric) array.
scipy.linalg.eig : Similar function in SciPy that also solves the
generalized eigenvalue problem.
scipy.linalg.schur : Best choice for unitary and other non-Hermitian
normal matrices.
Notes
-----
.. versionadded:: 1.8.0
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
This is implemented using the ``_geev`` LAPACK routines which compute
the eigenvalues and eigenvectors of general square arrays.
The number `w` is an eigenvalue of `a` if there exists a vector `v` such
that ``a @ v = w * v``. Thus, the arrays `a`, `eigenvalues`, and
`eigenvectors` satisfy the equations ``a @ eigenvectors[:,i] =
eigenvalues[i] * eigenvectors[:,i]`` for :math:`i \in \{0,...,M-1\}`.
The array `eigenvectors` may not be of maximum rank, that is, some of the
columns may be linearly dependent, although round-off error may obscure
that fact. If the eigenvalues are all different, then theoretically the
eigenvectors are linearly independent and `a` can be diagonalized by a
similarity transformation using `eigenvectors`, i.e, ``inv(eigenvectors) @
a @ eigenvectors`` is diagonal.
For non-Hermitian normal matrices the SciPy function `scipy.linalg.schur`
is preferred because the matrix `eigenvectors` is guaranteed to be
unitary, which is not the case when using `eig`. The Schur factorization
produces an upper triangular matrix rather than a diagonal matrix, but for
normal matrices only the diagonal of the upper triangular matrix is
needed, the rest is roundoff error.
Finally, it is emphasized that `eigenvectors` consists of the *right* (as
in right-hand side) eigenvectors of `a`. A vector `y` satisfying ``y.T @ a
= z * y.T`` for some number `z` is called a *left* eigenvector of `a`,
and, in general, the left and right eigenvectors of a matrix are not
necessarily the (perhaps conjugate) transposes of each other.
References
----------
G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL,
Academic Press, Inc., 1980, Various pp.
Examples
--------
>>> import numpy as np
>>> from numpy import linalg as LA
(Almost) trivial example with real eigenvalues and eigenvectors.
>>> eigenvalues, eigenvectors = LA.eig(np.diag((1, 2, 3)))
>>> eigenvalues
array([1., 2., 3.])
>>> eigenvectors
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
Real matrix possessing complex eigenvalues and eigenvectors;
note that the eigenvalues are complex conjugates of each other.
>>> eigenvalues, eigenvectors = LA.eig(np.array([[1, -1], [1, 1]]))
>>> eigenvalues
array([1.+1.j, 1.-1.j])
>>> eigenvectors
array([[0.70710678+0.j , 0.70710678-0.j ],
[0. -0.70710678j, 0. +0.70710678j]])
Complex-valued matrix with real eigenvalues (but complex-valued
eigenvectors); note that ``a.conj().T == a``, i.e., `a` is Hermitian.
>>> a = np.array([[1, 1j], [-1j, 1]])
>>> eigenvalues, eigenvectors = LA.eig(a)
>>> eigenvalues
array([2.+0.j, 0.+0.j])
>>> eigenvectors
array([[ 0. +0.70710678j, 0.70710678+0.j ], # may vary
[ 0.70710678+0.j , -0. +0.70710678j]])
Be careful about round-off error!
>>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
>>> # Theor. eigenvalues are 1 +/- 1e-9
>>> eigenvalues, eigenvectors = LA.eig(a)
>>> eigenvalues
array([1., 1.])
>>> eigenvectors
array([[1., 0.],
[0., 1.]])
eigh(a, UPLO='L')
Return the eigenvalues and eigenvectors of a complex Hermitian
(conjugate symmetric) or a real symmetric matrix.
Returns two objects, a 1-D array containing the eigenvalues of `a`, and
a 2-D square array or matrix (depending on the input type) of the
corresponding eigenvectors (in columns).
Parameters
----------
a : (..., M, M) array
Hermitian or real symmetric matrices whose eigenvalues and
eigenvectors are to be computed.
UPLO : {'L', 'U'}, optional
Specifies whether the calculation is done with the lower triangular
part of `a` ('L', default) or the upper triangular part ('U').
Irrespective of this value only the real parts of the diagonal will
be considered in the computation to preserve the notion of a Hermitian
matrix. It therefore follows that the imaginary part of the diagonal
will always be treated as zero.
Returns
-------
A namedtuple with the following attributes:
eigenvalues : (..., M) ndarray
The eigenvalues in ascending order, each repeated according to
its multiplicity.
eigenvectors : {(..., M, M) ndarray, (..., M, M) matrix}
The column ``eigenvectors[:, i]`` is the normalized eigenvector
corresponding to the eigenvalue ``eigenvalues[i]``. Will return a
matrix object if `a` is a matrix object.
Raises
------
LinAlgError
If the eigenvalue computation does not converge.
See Also
--------
eigvalsh : eigenvalues of real symmetric or complex Hermitian
(conjugate symmetric) arrays.
eig : eigenvalues and right eigenvectors for non-symmetric arrays.
eigvals : eigenvalues of non-symmetric arrays.
scipy.linalg.eigh : Similar function in SciPy (but also solves the
generalized eigenvalue problem).
Notes
-----
.. versionadded:: 1.8.0
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
The eigenvalues/eigenvectors are computed using LAPACK routines ``_syevd``,
``_heevd``.
The eigenvalues of real symmetric or complex Hermitian matrices are always
real. [1]_ The array `eigenvalues` of (column) eigenvectors is unitary and
`a`, `eigenvalues`, and `eigenvectors` satisfy the equations ``dot(a,
eigenvectors[:, i]) = eigenvalues[i] * eigenvectors[:, i]``.
References
----------
.. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
FL, Academic Press, Inc., 1980, pg. 222.
Examples
--------
>>> import numpy as np
>>> from numpy import linalg as LA
>>> a = np.array([[1, -2j], [2j, 5]])
>>> a
array([[ 1.+0.j, -0.-2.j],
[ 0.+2.j, 5.+0.j]])
>>> eigenvalues, eigenvectors = LA.eigh(a)
>>> eigenvalues
array([0.17157288, 5.82842712])
>>> eigenvectors
array([[-0.92387953+0.j , -0.38268343+0.j ], # may vary
[ 0. +0.38268343j, 0. -0.92387953j]])
>>> (np.dot(a, eigenvectors[:, 0]) -
... eigenvalues[0] * eigenvectors[:, 0]) # verify 1st eigenval/vec pair
array([5.55111512e-17+0.0000000e+00j, 0.00000000e+00+1.2490009e-16j])
>>> (np.dot(a, eigenvectors[:, 1]) -
... eigenvalues[1] * eigenvectors[:, 1]) # verify 2nd eigenval/vec pair
array([0.+0.j, 0.+0.j])
>>> A = np.matrix(a) # what happens if input is a matrix object
>>> A
matrix([[ 1.+0.j, -0.-2.j],
[ 0.+2.j, 5.+0.j]])
>>> eigenvalues, eigenvectors = LA.eigh(A)
>>> eigenvalues
array([0.17157288, 5.82842712])
>>> eigenvectors
matrix([[-0.92387953+0.j , -0.38268343+0.j ], # may vary
[ 0. +0.38268343j, 0. -0.92387953j]])
>>> # demonstrate the treatment of the imaginary part of the diagonal
>>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
>>> a
array([[5.+2.j, 9.-2.j],
[0.+2.j, 2.-1.j]])
>>> # with UPLO='L' this is numerically equivalent to using LA.eig() with:
>>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
>>> b
array([[5.+0.j, 0.-2.j],
[0.+2.j, 2.+0.j]])
>>> wa, va = LA.eigh(a)
>>> wb, vb = LA.eig(b)
>>> wa
array([1., 6.])
>>> wb
array([6.+0.j, 1.+0.j])
>>> va
array([[-0.4472136 +0.j , -0.89442719+0.j ], # may vary
[ 0. +0.89442719j, 0. -0.4472136j ]])
>>> vb
array([[ 0.89442719+0.j , -0. +0.4472136j],
[-0. +0.4472136j, 0.89442719+0.j ]])
eigvals(a)
Compute the eigenvalues of a general matrix.
Main difference between `eigvals` and `eig`: the eigenvectors aren't
returned.
Parameters
----------
a : (..., M, M) array_like
A complex- or real-valued matrix whose eigenvalues will be computed.
Returns
-------
w : (..., M,) ndarray
The eigenvalues, each repeated according to its multiplicity.
They are not necessarily ordered, nor are they necessarily
real for real matrices.
Raises
------
LinAlgError
If the eigenvalue computation does not converge.
See Also
--------
eig : eigenvalues and right eigenvectors of general arrays
eigvalsh : eigenvalues of real symmetric or complex Hermitian
(conjugate symmetric) arrays.
eigh : eigenvalues and eigenvectors of real symmetric or complex
Hermitian (conjugate symmetric) arrays.
scipy.linalg.eigvals : Similar function in SciPy.
Notes
-----
.. versionadded:: 1.8.0
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
This is implemented using the ``_geev`` LAPACK routines which compute
the eigenvalues and eigenvectors of general square arrays.
Examples
--------
Illustration, using the fact that the eigenvalues of a diagonal matrix
are its diagonal elements, that multiplying a matrix on the left
by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose
of `Q`), preserves the eigenvalues of the "middle" matrix. In other words,
if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as
``A``:
>>> import numpy as np
>>> from numpy import linalg as LA
>>> x = np.random.random()
>>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]])
>>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :])
(1.0, 1.0, 0.0)
Now multiply a diagonal matrix by ``Q`` on one side and
by ``Q.T`` on the other:
>>> D = np.diag((-1,1))
>>> LA.eigvals(D)
array([-1., 1.])
>>> A = np.dot(Q, D)
>>> A = np.dot(A, Q.T)
>>> LA.eigvals(A)
array([ 1., -1.]) # random
eigvalsh(a, UPLO='L')
Compute the eigenvalues of a complex Hermitian or real symmetric matrix.
Main difference from eigh: the eigenvectors are not computed.
Parameters
----------
a : (..., M, M) array_like
A complex- or real-valued matrix whose eigenvalues are to be
computed.
UPLO : {'L', 'U'}, optional
Specifies whether the calculation is done with the lower triangular
part of `a` ('L', default) or the upper triangular part ('U').
Irrespective of this value only the real parts of the diagonal will
be considered in the computation to preserve the notion of a Hermitian
matrix. It therefore follows that the imaginary part of the diagonal
will always be treated as zero.
Returns
-------
w : (..., M,) ndarray
The eigenvalues in ascending order, each repeated according to
its multiplicity.
Raises
------
LinAlgError
If the eigenvalue computation does not converge.
See Also
--------
eigh : eigenvalues and eigenvectors of real symmetric or complex Hermitian
(conjugate symmetric) arrays.
eigvals : eigenvalues of general real or complex arrays.
eig : eigenvalues and right eigenvectors of general real or complex
arrays.
scipy.linalg.eigvalsh : Similar function in SciPy.
Notes
-----
.. versionadded:: 1.8.0
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
The eigenvalues are computed using LAPACK routines ``_syevd``, ``_heevd``.
Examples
--------
>>> import numpy as np
>>> from numpy import linalg as LA
>>> a = np.array([[1, -2j], [2j, 5]])
>>> LA.eigvalsh(a)
array([ 0.17157288, 5.82842712]) # may vary
>>> # demonstrate the treatment of the imaginary part of the diagonal
>>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
>>> a
array([[5.+2.j, 9.-2.j],
[0.+2.j, 2.-1.j]])
>>> # with UPLO='L' this is numerically equivalent to using LA.eigvals()
>>> # with:
>>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
>>> b
array([[5.+0.j, 0.-2.j],
[0.+2.j, 2.+0.j]])
>>> wa = LA.eigvalsh(a)
>>> wb = LA.eigvals(b)
>>> wa; wb
array([1., 6.])
array([6.+0.j, 1.+0.j])
inv(a)
Compute the inverse of a matrix.
Given a square matrix `a`, return the matrix `ainv` satisfying
``a @ ainv = ainv @ a = eye(a.shape[0])``.
Parameters
----------
a : (..., M, M) array_like
Matrix to be inverted.
Returns
-------
ainv : (..., M, M) ndarray or matrix
Inverse of the matrix `a`.
Raises
------
LinAlgError
If `a` is not square or inversion fails.
See Also
--------
scipy.linalg.inv : Similar function in SciPy.
numpy.linalg.cond : Compute the condition number of a matrix.
numpy.linalg.svd : Compute the singular value decomposition of a matrix.
Notes
-----
.. versionadded:: 1.8.0
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
If `a` is detected to be singular, a `LinAlgError` is raised. If `a` is
ill-conditioned, a `LinAlgError` may or may not be raised, and results may
be inaccurate due to floating-point errors.
References
----------
.. [1] Wikipedia, "Condition number",
https://en.wikipedia.org/wiki/Condition_number
Examples
--------
>>> import numpy as np
>>> from numpy.linalg import inv
>>> a = np.array([[1., 2.], [3., 4.]])
>>> ainv = inv(a)
>>> np.allclose(a @ ainv, np.eye(2))
True
>>> np.allclose(ainv @ a, np.eye(2))
True
If a is a matrix object, then the return value is a matrix as well:
>>> ainv = inv(np.matrix(a))
>>> ainv
matrix([[-2. , 1. ],
[ 1.5, -0.5]])
Inverses of several matrices can be computed at once:
>>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]])
>>> inv(a)
array([[[-2. , 1. ],
[ 1.5 , -0.5 ]],
[[-1.25, 0.75],
[ 0.75, -0.25]]])
If a matrix is close to singular, the computed inverse may not satisfy
``a @ ainv = ainv @ a = eye(a.shape[0])`` even if a `LinAlgError`
is not raised:
>>> a = np.array([[2,4,6],[2,0,2],[6,8,14]])
>>> inv(a) # No errors raised
array([[-1.12589991e+15, -5.62949953e+14, 5.62949953e+14],
[-1.12589991e+15, -5.62949953e+14, 5.62949953e+14],
[ 1.12589991e+15, 5.62949953e+14, -5.62949953e+14]])
>>> a @ inv(a)
array([[ 0. , -0.5 , 0. ], # may vary
[-0.5 , 0.625, 0.25 ],
[ 0. , 0. , 1. ]])
To detect ill-conditioned matrices, you can use `numpy.linalg.cond` to
compute its *condition number* [1]_. The larger the condition number, the
more ill-conditioned the matrix is. As a rule of thumb, if the condition
number ``cond(a) = 10**k``, then you may lose up to ``k`` digits of
accuracy on top of what would be lost to the numerical method due to loss
of precision from arithmetic methods.
>>> from numpy.linalg import cond
>>> cond(a)
np.float64(8.659885634118668e+17) # may vary
It is also possible to detect ill-conditioning by inspecting the matrix's
singular values directly. The ratio between the largest and the smallest
singular value is the condition number:
>>> from numpy.linalg import svd
>>> sigma = svd(a, compute_uv=False) # Do not compute singular vectors
>>> sigma.max()/sigma.min()
8.659885634118668e+17 # may vary
lstsq(a, b, rcond=None)
Return the least-squares solution to a linear matrix equation.
Computes the vector `x` that approximately solves the equation
``a @ x = b``. The equation may be under-, well-, or over-determined
(i.e., the number of linearly independent rows of `a` can be less than,
equal to, or greater than its number of linearly independent columns).
If `a` is square and of full rank, then `x` (but for round-off error)
is the "exact" solution of the equation. Else, `x` minimizes the
Euclidean 2-norm :math:`||b - ax||`. If there are multiple minimizing
solutions, the one with the smallest 2-norm :math:`||x||` is returned.
Parameters
----------
a : (M, N) array_like
"Coefficient" matrix.
b : {(M,), (M, K)} array_like
Ordinate or "dependent variable" values. If `b` is two-dimensional,
the least-squares solution is calculated for each of the `K` columns
of `b`.
rcond : float, optional
Cut-off ratio for small singular values of `a`.
For the purposes of rank determination, singular values are treated
as zero if they are smaller than `rcond` times the largest singular
value of `a`.
The default uses the machine precision times ``max(M, N)``. Passing
``-1`` will use machine precision.
.. versionchanged:: 2.0
Previously, the default was ``-1``, but a warning was given that
this would change.
Returns
-------
x : {(N,), (N, K)} ndarray
Least-squares solution. If `b` is two-dimensional,
the solutions are in the `K` columns of `x`.
residuals : {(1,), (K,), (0,)} ndarray
Sums of squared residuals: Squared Euclidean 2-norm for each column in
``b - a @ x``.
If the rank of `a` is < N or M <= N, this is an empty array.
If `b` is 1-dimensional, this is a (1,) shape array.
Otherwise the shape is (K,).
rank : int
Rank of matrix `a`.
s : (min(M, N),) ndarray
Singular values of `a`.
Raises
------
LinAlgError
If computation does not converge.
See Also
--------
scipy.linalg.lstsq : Similar function in SciPy.
Notes
-----
If `b` is a matrix, then all array results are returned as matrices.
Examples
--------
Fit a line, ``y = mx + c``, through some noisy data-points:
>>> import numpy as np
>>> x = np.array([0, 1, 2, 3])
>>> y = np.array([-1, 0.2, 0.9, 2.1])
By examining the coefficients, we see that the line should have a
gradient of roughly 1 and cut the y-axis at, more or less, -1.
We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`:
>>> A = np.vstack([x, np.ones(len(x))]).T
>>> A
array([[ 0., 1.],
[ 1., 1.],
[ 2., 1.],
[ 3., 1.]])
>>> m, c = np.linalg.lstsq(A, y)[0]
>>> m, c
(1.0 -0.95) # may vary
Plot the data along with the fitted line:
>>> import matplotlib.pyplot as plt
>>> _ = plt.plot(x, y, 'o', label='Original data', markersize=10)
>>> _ = plt.plot(x, m*x + c, 'r', label='Fitted line')
>>> _ = plt.legend()
>>> plt.show()
matmul(x1, x2, /)
Computes the matrix product.
This function is Array API compatible, contrary to
:func:`numpy.matmul`.
Parameters
----------
x1 : array_like
The first input array.
x2 : array_like
The second input array.
Returns
-------
out : ndarray
The matrix product of the inputs.
This is a scalar only when both ``x1``, ``x2`` are 1-d vectors.
Raises
------
ValueError
If the last dimension of ``x1`` is not the same size as
the second-to-last dimension of ``x2``.
If a scalar value is passed in.
See Also
--------
numpy.matmul
Examples
--------
For 2-D arrays it is the matrix product:
>>> a = np.array([[1, 0],
... [0, 1]])
>>> b = np.array([[4, 1],
... [2, 2]])
>>> np.linalg.matmul(a, b)
array([[4, 1],
[2, 2]])
For 2-D mixed with 1-D, the result is the usual.
>>> a = np.array([[1, 0],
... [0, 1]])
>>> b = np.array([1, 2])
>>> np.linalg.matmul(a, b)
array([1, 2])
>>> np.linalg.matmul(b, a)
array([1, 2])
Broadcasting is conventional for stacks of arrays
>>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4))
>>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2))
>>> np.linalg.matmul(a,b).shape
(2, 2, 2)
>>> np.linalg.matmul(a, b)[0, 1, 1]
98
>>> sum(a[0, 1, :] * b[0 , :, 1])
98
Vector, vector returns the scalar inner product, but neither argument
is complex-conjugated:
>>> np.linalg.matmul([2j, 3j], [2j, 3j])
(-13+0j)
Scalar multiplication raises an error.
>>> np.linalg.matmul([1,2], 3)
Traceback (most recent call last):
...
ValueError: matmul: Input operand 1 does not have enough dimensions ...
matrix_norm(x, /, *, keepdims=False, ord='fro')
Computes the matrix norm of a matrix (or a stack of matrices) ``x``.
This function is Array API compatible.
Parameters
----------
x : array_like
Input array having shape (..., M, N) and whose two innermost
dimensions form ``MxN`` matrices.
keepdims : bool, optional
If this is set to True, the axes which are normed over are left in
the result as dimensions with size one. Default: False.
ord : {1, -1, 2, -2, inf, -inf, 'fro', 'nuc'}, optional
The order of the norm. For details see the table under ``Notes``
in `numpy.linalg.norm`.
See Also
--------
numpy.linalg.norm : Generic norm function
Examples
--------
>>> from numpy import linalg as LA
>>> a = np.arange(9) - 4
>>> a
array([-4, -3, -2, ..., 2, 3, 4])
>>> b = a.reshape((3, 3))
>>> b
array([[-4, -3, -2],
[-1, 0, 1],
[ 2, 3, 4]])
>>> LA.matrix_norm(b)
7.745966692414834
>>> LA.matrix_norm(b, ord='fro')
7.745966692414834
>>> LA.matrix_norm(b, ord=np.inf)
9.0
>>> LA.matrix_norm(b, ord=-np.inf)
2.0
>>> LA.matrix_norm(b, ord=1)
7.0
>>> LA.matrix_norm(b, ord=-1)
6.0
>>> LA.matrix_norm(b, ord=2)
7.3484692283495345
>>> LA.matrix_norm(b, ord=-2)
1.8570331885190563e-016 # may vary
matrix_power(a, n)
Raise a square matrix to the (integer) power `n`.
For positive integers `n`, the power is computed by repeated matrix
squarings and matrix multiplications. If ``n == 0``, the identity matrix
of the same shape as M is returned. If ``n < 0``, the inverse
is computed and then raised to the ``abs(n)``.
.. note:: Stacks of object matrices are not currently supported.
Parameters
----------
a : (..., M, M) array_like
Matrix to be "powered".
n : int
The exponent can be any integer or long integer, positive,
negative, or zero.
Returns
-------
a**n : (..., M, M) ndarray or matrix object
The return value is the same shape and type as `M`;
if the exponent is positive or zero then the type of the
elements is the same as those of `M`. If the exponent is
negative the elements are floating-point.
Raises
------
LinAlgError
For matrices that are not square or that (for negative powers) cannot
be inverted numerically.
Examples
--------
>>> import numpy as np
>>> from numpy.linalg import matrix_power
>>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
>>> matrix_power(i, 3) # should = -i
array([[ 0, -1],
[ 1, 0]])
>>> matrix_power(i, 0)
array([[1, 0],
[0, 1]])
>>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
array([[ 0., 1.],
[-1., 0.]])
Somewhat more sophisticated example
>>> q = np.zeros((4, 4))
>>> q[0:2, 0:2] = -i
>>> q[2:4, 2:4] = i
>>> q # one of the three quaternion units not equal to 1
array([[ 0., -1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.],
[ 0., 0., -1., 0.]])
>>> matrix_power(q, 2) # = -np.eye(4)
array([[-1., 0., 0., 0.],
[ 0., -1., 0., 0.],
[ 0., 0., -1., 0.],
[ 0., 0., 0., -1.]])
matrix_rank(A, tol=None, hermitian=False, *, rtol=None)
Return matrix rank of array using SVD method
Rank of the array is the number of singular values of the array that are
greater than `tol`.
.. versionchanged:: 1.14
Can now operate on stacks of matrices
Parameters
----------
A : {(M,), (..., M, N)} array_like
Input vector or stack of matrices.
tol : (...) array_like, float, optional
Threshold below which SVD values are considered zero. If `tol` is
None, and ``S`` is an array with singular values for `M`, and
``eps`` is the epsilon value for datatype of ``S``, then `tol` is
set to ``S.max() * max(M, N) * eps``.
.. versionchanged:: 1.14
Broadcasted against the stack of matrices
hermitian : bool, optional
If True, `A` is assumed to be Hermitian (symmetric if real-valued),
enabling a more efficient method for finding singular values.
Defaults to False.
.. versionadded:: 1.14
rtol : (...) array_like, float, optional
Parameter for the relative tolerance component. Only ``tol`` or
``rtol`` can be set at a time. Defaults to ``max(M, N) * eps``.
.. versionadded:: 2.0.0
Returns
-------
rank : (...) array_like
Rank of A.
Notes
-----
The default threshold to detect rank deficiency is a test on the magnitude
of the singular values of `A`. By default, we identify singular values
less than ``S.max() * max(M, N) * eps`` as indicating rank deficiency
(with the symbols defined above). This is the algorithm MATLAB uses [1].
It also appears in *Numerical recipes* in the discussion of SVD solutions
for linear least squares [2].
This default threshold is designed to detect rank deficiency accounting
for the numerical errors of the SVD computation. Imagine that there
is a column in `A` that is an exact (in floating point) linear combination
of other columns in `A`. Computing the SVD on `A` will not produce
a singular value exactly equal to 0 in general: any difference of
the smallest SVD value from 0 will be caused by numerical imprecision
in the calculation of the SVD. Our threshold for small SVD values takes
this numerical imprecision into account, and the default threshold will
detect such numerical rank deficiency. The threshold may declare a matrix
`A` rank deficient even if the linear combination of some columns of `A`
is not exactly equal to another column of `A` but only numerically very
close to another column of `A`.
We chose our default threshold because it is in wide use. Other thresholds
are possible. For example, elsewhere in the 2007 edition of *Numerical
recipes* there is an alternative threshold of ``S.max() *
np.finfo(A.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe
this threshold as being based on "expected roundoff error" (p 71).
The thresholds above deal with floating point roundoff error in the
calculation of the SVD. However, you may have more information about
the sources of error in `A` that would make you consider other tolerance
values to detect *effective* rank deficiency. The most useful measure
of the tolerance depends on the operations you intend to use on your
matrix. For example, if your data come from uncertain measurements with
uncertainties greater than floating point epsilon, choosing a tolerance
near that uncertainty may be preferable. The tolerance may be absolute
if the uncertainties are absolute rather than relative.
References
----------
.. [1] MATLAB reference documentation, "Rank"
https://www.mathworks.com/help/techdoc/ref/rank.html
.. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery,
"Numerical Recipes (3rd edition)", Cambridge University Press, 2007,
page 795.
Examples
--------
>>> import numpy as np
>>> from numpy.linalg import matrix_rank
>>> matrix_rank(np.eye(4)) # Full rank matrix
4
>>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix
>>> matrix_rank(I)
3
>>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0
1
>>> matrix_rank(np.zeros((4,)))
0
matrix_transpose(x, /)
Transposes a matrix (or a stack of matrices) ``x``.
This function is Array API compatible.
Parameters
----------
x : array_like
Input array having shape (..., M, N) and whose two innermost
dimensions form ``MxN`` matrices.
Returns
-------
out : ndarray
An array containing the transpose for each matrix and having shape
(..., N, M).
See Also
--------
transpose : Generic transpose method.
Examples
--------
>>> import numpy as np
>>> np.matrix_transpose([[1, 2], [3, 4]])
array([[1, 3],
[2, 4]])
>>> np.matrix_transpose([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
array([[[1, 3],
[2, 4]],
[[5, 7],
[6, 8]]])
multi_dot(arrays, *, out=None)
Compute the dot product of two or more arrays in a single function call,
while automatically selecting the fastest evaluation order.
`multi_dot` chains `numpy.dot` and uses optimal parenthesization
of the matrices [1]_ [2]_. Depending on the shapes of the matrices,
this can speed up the multiplication a lot.
If the first argument is 1-D it is treated as a row vector.
If the last argument is 1-D it is treated as a column vector.
The other arguments must be 2-D.
Think of `multi_dot` as::
def multi_dot(arrays): return functools.reduce(np.dot, arrays)
Parameters
----------
arrays : sequence of array_like
If the first argument is 1-D it is treated as row vector.
If the last argument is 1-D it is treated as column vector.
The other arguments must be 2-D.
out : ndarray, optional
Output argument. This must have the exact kind that would be returned
if it was not used. In particular, it must have the right type, must be
C-contiguous, and its dtype must be the dtype that would be returned
for `dot(a, b)`. This is a performance feature. Therefore, if these
conditions are not met, an exception is raised, instead of attempting
to be flexible.
.. versionadded:: 1.19.0
Returns
-------
output : ndarray
Returns the dot product of the supplied arrays.
See Also
--------
numpy.dot : dot multiplication with two arguments.
References
----------
.. [1] Cormen, "Introduction to Algorithms", Chapter 15.2, p. 370-378
.. [2] https://en.wikipedia.org/wiki/Matrix_chain_multiplication
Examples
--------
`multi_dot` allows you to write::
>>> import numpy as np
>>> from numpy.linalg import multi_dot
>>> # Prepare some data
>>> A = np.random.random((10000, 100))
>>> B = np.random.random((100, 1000))
>>> C = np.random.random((1000, 5))
>>> D = np.random.random((5, 333))
>>> # the actual dot multiplication
>>> _ = multi_dot([A, B, C, D])
instead of::
>>> _ = np.dot(np.dot(np.dot(A, B), C), D)
>>> # or
>>> _ = A.dot(B).dot(C).dot(D)
Notes
-----
The cost for a matrix multiplication can be calculated with the
following function::
def cost(A, B):
return A.shape[0] * A.shape[1] * B.shape[1]
Assume we have three matrices
:math:`A_{10x100}, B_{100x5}, C_{5x50}`.
The costs for the two different parenthesizations are as follows::
cost((AB)C) = 10*100*5 + 10*5*50 = 5000 + 2500 = 7500
cost(A(BC)) = 10*100*50 + 100*5*50 = 50000 + 25000 = 75000
norm(x, ord=None, axis=None, keepdims=False)
Matrix or vector norm.
This function is able to return one of eight different matrix norms,
or one of an infinite number of vector norms (described below), depending
on the value of the ``ord`` parameter.
Parameters
----------
x : array_like
Input array. If `axis` is None, `x` must be 1-D or 2-D, unless `ord`
is None. If both `axis` and `ord` are None, the 2-norm of
``x.ravel`` will be returned.
ord : {non-zero int, inf, -inf, 'fro', 'nuc'}, optional
Order of the norm (see table under ``Notes``). inf means numpy's
`inf` object. The default is None.
axis : {None, int, 2-tuple of ints}, optional.
If `axis` is an integer, it specifies the axis of `x` along which to
compute the vector norms. If `axis` is a 2-tuple, it specifies the
axes that hold 2-D matrices, and the matrix norms of these matrices
are computed. If `axis` is None then either a vector norm (when `x`
is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default
is None.
.. versionadded:: 1.8.0
keepdims : bool, optional
If this is set to True, the axes which are normed over are left in the
result as dimensions with size one. With this option the result will
broadcast correctly against the original `x`.
.. versionadded:: 1.10.0
Returns
-------
n : float or ndarray
Norm of the matrix or vector(s).
See Also
--------
scipy.linalg.norm : Similar function in SciPy.
Notes
-----
For values of ``ord < 1``, the result is, strictly speaking, not a
mathematical 'norm', but it may still be useful for various numerical
purposes.
The following norms can be calculated:
===== ============================ ==========================
ord norm for matrices norm for vectors
===== ============================ ==========================
None Frobenius norm 2-norm
'fro' Frobenius norm --
'nuc' nuclear norm --
inf max(sum(abs(x), axis=1)) max(abs(x))
-inf min(sum(abs(x), axis=1)) min(abs(x))
0 -- sum(x != 0)
1 max(sum(abs(x), axis=0)) as below
-1 min(sum(abs(x), axis=0)) as below
2 2-norm (largest sing. value) as below
-2 smallest singular value as below
other -- sum(abs(x)**ord)**(1./ord)
===== ============================ ==========================
The Frobenius norm is given by [1]_:
:math:`||A||_F = [\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
The nuclear norm is the sum of the singular values.
Both the Frobenius and nuclear norm orders are only defined for
matrices and raise a ValueError when ``x.ndim != 2``.
References
----------
.. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
Examples
--------
>>> import numpy as np
>>> from numpy import linalg as LA
>>> a = np.arange(9) - 4
>>> a
array([-4, -3, -2, ..., 2, 3, 4])
>>> b = a.reshape((3, 3))
>>> b
array([[-4, -3, -2],
[-1, 0, 1],
[ 2, 3, 4]])
>>> LA.norm(a)
7.745966692414834
>>> LA.norm(b)
7.745966692414834
>>> LA.norm(b, 'fro')
7.745966692414834
>>> LA.norm(a, np.inf)
4.0
>>> LA.norm(b, np.inf)
9.0
>>> LA.norm(a, -np.inf)
0.0
>>> LA.norm(b, -np.inf)
2.0
>>> LA.norm(a, 1)
20.0
>>> LA.norm(b, 1)
7.0
>>> LA.norm(a, -1)
-4.6566128774142013e-010
>>> LA.norm(b, -1)
6.0
>>> LA.norm(a, 2)
7.745966692414834
>>> LA.norm(b, 2)
7.3484692283495345
>>> LA.norm(a, -2)
0.0
>>> LA.norm(b, -2)
1.8570331885190563e-016 # may vary
>>> LA.norm(a, 3)
5.8480354764257312 # may vary
>>> LA.norm(a, -3)
0.0
Using the `axis` argument to compute vector norms:
>>> c = np.array([[ 1, 2, 3],
... [-1, 1, 4]])
>>> LA.norm(c, axis=0)
array([ 1.41421356, 2.23606798, 5. ])
>>> LA.norm(c, axis=1)
array([ 3.74165739, 4.24264069])
>>> LA.norm(c, ord=1, axis=1)
array([ 6., 6.])
Using the `axis` argument to compute matrix norms:
>>> m = np.arange(8).reshape(2,2,2)
>>> LA.norm(m, axis=(1,2))
array([ 3.74165739, 11.22497216])
>>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :])
(3.7416573867739413, 11.224972160321824)
outer(x1, x2, /)
Compute the outer product of two vectors.
This function is Array API compatible. Compared to ``np.outer``
it accepts 1-dimensional inputs only.
Parameters
----------
x1 : (M,) array_like
One-dimensional input array of size ``N``.
Must have a numeric data type.
x2 : (N,) array_like
One-dimensional input array of size ``M``.
Must have a numeric data type.
Returns
-------
out : (M, N) ndarray
``out[i, j] = a[i] * b[j]``
See also
--------
outer
Examples
--------
Make a (*very* coarse) grid for computing a Mandelbrot set:
>>> rl = np.linalg.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.linalg.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.linalg.outer(x, [1, 2, 3])
array([['a', 'aa', 'aaa'],
['b', 'bb', 'bbb'],
['c', 'cc', 'ccc']], dtype=object)
pinv(a, rcond=None, hermitian=False, *, rtol=<no value>)
Compute the (Moore-Penrose) pseudo-inverse of a matrix.
Calculate the generalized inverse of a matrix using its
singular-value decomposition (SVD) and including all
*large* singular values.
.. versionchanged:: 1.14
Can now operate on stacks of matrices
Parameters
----------
a : (..., M, N) array_like
Matrix or stack of matrices to be pseudo-inverted.
rcond : (...) array_like of float, optional
Cutoff for small singular values.
Singular values less than or equal to
``rcond * largest_singular_value`` are set to zero.
Broadcasts against the stack of matrices. Default: ``1e-15``.
hermitian : bool, optional
If True, `a` is assumed to be Hermitian (symmetric if real-valued),
enabling a more efficient method for finding singular values.
Defaults to False.
.. versionadded:: 1.17.0
rtol : (...) array_like of float, optional
Same as `rcond`, but it's an Array API compatible parameter name.
Only `rcond` or `rtol` can be set at a time. If none of them are
provided then NumPy's ``1e-15`` default is used. If ``rtol=None``
is passed then the API standard default is used.
.. versionadded:: 2.0.0
Returns
-------
B : (..., N, M) ndarray
The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so
is `B`.
Raises
------
LinAlgError
If the SVD computation does not converge.
See Also
--------
scipy.linalg.pinv : Similar function in SciPy.
scipy.linalg.pinvh : Compute the (Moore-Penrose) pseudo-inverse of a
Hermitian matrix.
Notes
-----
The pseudo-inverse of a matrix A, denoted :math:`A^+`, is
defined as: "the matrix that 'solves' [the least-squares problem]
:math:`Ax = b`," i.e., if :math:`\bar{x}` is said solution, then
:math:`A^+` is that matrix such that :math:`\bar{x} = A^+b`.
It can be shown that if :math:`Q_1 \Sigma Q_2^T = A` is the singular
value decomposition of A, then
:math:`A^+ = Q_2 \Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are
orthogonal matrices, :math:`\Sigma` is a diagonal matrix consisting
of A's so-called singular values, (followed, typically, by
zeros), and then :math:`\Sigma^+` is simply the diagonal matrix
consisting of the reciprocals of A's singular values
(again, followed by zeros). [1]_
References
----------
.. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
FL, Academic Press, Inc., 1980, pp. 139-142.
Examples
--------
The following example checks that ``a * a+ * a == a`` and
``a+ * a * a+ == a+``:
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> a = rng.normal(size=(9, 6))
>>> B = np.linalg.pinv(a)
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
True
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
True
qr(a, mode='reduced')
Compute the qr factorization of a matrix.
Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is
upper-triangular.
Parameters
----------
a : array_like, shape (..., M, N)
An array-like object with the dimensionality of at least 2.
mode : {'reduced', 'complete', 'r', 'raw'}, optional, default: 'reduced'
If K = min(M, N), then
* 'reduced' : returns Q, R with dimensions (..., M, K), (..., K, N)
* 'complete' : returns Q, R with dimensions (..., M, M), (..., M, N)
* 'r' : returns R only with dimensions (..., K, N)
* 'raw' : returns h, tau with dimensions (..., N, M), (..., K,)
The options 'reduced', 'complete, and 'raw' are new in numpy 1.8,
see the notes for more information. The default is 'reduced', and to
maintain backward compatibility with earlier versions of numpy both
it and the old default 'full' can be omitted. Note that array h
returned in 'raw' mode is transposed for calling Fortran. The
'economic' mode is deprecated. The modes 'full' and 'economic' may
be passed using only the first letter for backwards compatibility,
but all others must be spelled out. See the Notes for more
explanation.
Returns
-------
When mode is 'reduced' or 'complete', the result will be a namedtuple with
the attributes `Q` and `R`.
Q : ndarray of float or complex, optional
A matrix with orthonormal columns. When mode = 'complete' the
result is an orthogonal/unitary matrix depending on whether or not
a is real/complex. The determinant may be either +/- 1 in that
case. In case the number of dimensions in the input array is
greater than 2 then a stack of the matrices with above properties
is returned.
R : ndarray of float or complex, optional
The upper-triangular matrix or a stack of upper-triangular
matrices if the number of dimensions in the input array is greater
than 2.
(h, tau) : ndarrays of np.double or np.cdouble, optional
The array h contains the Householder reflectors that generate q
along with r. The tau array contains scaling factors for the
reflectors. In the deprecated 'economic' mode only h is returned.
Raises
------
LinAlgError
If factoring fails.
See Also
--------
scipy.linalg.qr : Similar function in SciPy.
scipy.linalg.rq : Compute RQ decomposition of a matrix.
Notes
-----
This is an interface to the LAPACK routines ``dgeqrf``, ``zgeqrf``,
``dorgqr``, and ``zungqr``.
For more information on the qr factorization, see for example:
https://en.wikipedia.org/wiki/QR_factorization
Subclasses of `ndarray` are preserved except for the 'raw' mode. So if
`a` is of type `matrix`, all the return values will be matrices too.
New 'reduced', 'complete', and 'raw' options for mode were added in
NumPy 1.8.0 and the old option 'full' was made an alias of 'reduced'. In
addition the options 'full' and 'economic' were deprecated. Because
'full' was the previous default and 'reduced' is the new default,
backward compatibility can be maintained by letting `mode` default.
The 'raw' option was added so that LAPACK routines that can multiply
arrays by q using the Householder reflectors can be used. Note that in
this case the returned arrays are of type np.double or np.cdouble and
the h array is transposed to be FORTRAN compatible. No routines using
the 'raw' return are currently exposed by numpy, but some are available
in lapack_lite and just await the necessary work.
Examples
--------
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> a = rng.normal(size=(9, 6))
>>> Q, R = np.linalg.qr(a)
>>> np.allclose(a, np.dot(Q, R)) # a does equal QR
True
>>> R2 = np.linalg.qr(a, mode='r')
>>> np.allclose(R, R2) # mode='r' returns the same R as mode='full'
True
>>> a = np.random.normal(size=(3, 2, 2)) # Stack of 2 x 2 matrices as input
>>> Q, R = np.linalg.qr(a)
>>> Q.shape
(3, 2, 2)
>>> R.shape
(3, 2, 2)
>>> np.allclose(a, np.matmul(Q, R))
True
Example illustrating a common use of `qr`: solving of least squares
problems
What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for
the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points
and you'll see that it should be y0 = 0, m = 1.) The answer is provided
by solving the over-determined matrix equation ``Ax = b``, where::
A = array([[0, 1], [1, 1], [1, 1], [2, 1]])
x = array([[y0], [m]])
b = array([[1], [0], [2], [1]])
If A = QR such that Q is orthonormal (which is always possible via
Gram-Schmidt), then ``x = inv(R) * (Q.T) * b``. (In numpy practice,
however, we simply use `lstsq`.)
>>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]])
>>> A
array([[0, 1],
[1, 1],
[1, 1],
[2, 1]])
>>> b = np.array([1, 2, 2, 3])
>>> Q, R = np.linalg.qr(A)
>>> p = np.dot(Q.T, b)
>>> np.dot(np.linalg.inv(R), p)
array([ 1., 1.])
slogdet(a)
Compute the sign and (natural) logarithm of the determinant of an array.
If an array has a very small or very large determinant, then a call to
`det` may overflow or underflow. This routine is more robust against such
issues, because it computes the logarithm of the determinant rather than
the determinant itself.
Parameters
----------
a : (..., M, M) array_like
Input array, has to be a square 2-D array.
Returns
-------
A namedtuple with the following attributes:
sign : (...) array_like
A number representing the sign of the determinant. For a real matrix,
this is 1, 0, or -1. For a complex matrix, this is a complex number
with absolute value 1 (i.e., it is on the unit circle), or else 0.
logabsdet : (...) array_like
The natural log of the absolute value of the determinant.
If the determinant is zero, then `sign` will be 0 and `logabsdet`
will be -inf. In all cases, the determinant is equal to
``sign * np.exp(logabsdet)``.
See Also
--------
det
Notes
-----
.. versionadded:: 1.8.0
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
.. versionadded:: 1.6.0
The determinant is computed via LU factorization using the LAPACK
routine ``z/dgetrf``.
Examples
--------
The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``:
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> (sign, logabsdet) = np.linalg.slogdet(a)
>>> (sign, logabsdet)
(-1, 0.69314718055994529) # may vary
>>> sign * np.exp(logabsdet)
-2.0
Computing log-determinants for a stack of matrices:
>>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
>>> a.shape
(3, 2, 2)
>>> sign, logabsdet = np.linalg.slogdet(a)
>>> (sign, logabsdet)
(array([-1., -1., -1.]), array([ 0.69314718, 1.09861229, 2.07944154]))
>>> sign * np.exp(logabsdet)
array([-2., -3., -8.])
This routine succeeds where ordinary `det` does not:
>>> np.linalg.det(np.eye(500) * 0.1)
0.0
>>> np.linalg.slogdet(np.eye(500) * 0.1)
(1, -1151.2925464970228)
solve(a, b)
Solve a linear matrix equation, or system of linear scalar equations.
Computes the "exact" solution, `x`, of the well-determined, i.e., full
rank, linear matrix equation `ax = b`.
Parameters
----------
a : (..., M, M) array_like
Coefficient matrix.
b : {(M,), (..., M, K)}, array_like
Ordinate or "dependent variable" values.
Returns
-------
x : {(..., M,), (..., M, K)} ndarray
Solution to the system a x = b. Returned shape is (..., M) if b is
shape (M,) and (..., M, K) if b is (..., M, K), where the "..." part is
broadcasted between a and b.
Raises
------
LinAlgError
If `a` is singular or not square.
See Also
--------
scipy.linalg.solve : Similar function in SciPy.
Notes
-----
.. versionadded:: 1.8.0
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
The solutions are computed using LAPACK routine ``_gesv``.
`a` must be square and of full-rank, i.e., all rows (or, equivalently,
columns) must be linearly independent; if either is not true, use
`lstsq` for the least-squares best "solution" of the
system/equation.
.. versionchanged:: 2.0
The b array is only treated as a shape (M,) column vector if it is
exactly 1-dimensional. In all other instances it is treated as a stack
of (M, K) matrices. Previously b would be treated as a stack of (M,)
vectors if b.ndim was equal to a.ndim - 1.
References
----------
.. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
FL, Academic Press, Inc., 1980, pg. 22.
Examples
--------
Solve the system of equations:
``x0 + 2 * x1 = 1`` and
``3 * x0 + 5 * x1 = 2``:
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 5]])
>>> b = np.array([1, 2])
>>> x = np.linalg.solve(a, b)
>>> x
array([-1., 1.])
Check that the solution is correct:
>>> np.allclose(np.dot(a, x), b)
True
svd(a, full_matrices=True, compute_uv=True, hermitian=False)
Singular Value Decomposition.
When `a` is a 2D array, and ``full_matrices=False``, then it is
factorized as ``u @ np.diag(s) @ vh = (u * s) @ vh``, where
`u` and the Hermitian transpose of `vh` are 2D arrays with
orthonormal columns and `s` is a 1D array of `a`'s singular
values. When `a` is higher-dimensional, SVD is applied in
stacked mode as explained below.
Parameters
----------
a : (..., M, N) array_like
A real or complex array with ``a.ndim >= 2``.
full_matrices : bool, optional
If True (default), `u` and `vh` have the shapes ``(..., M, M)`` and
``(..., N, N)``, respectively. Otherwise, the shapes are
``(..., M, K)`` and ``(..., K, N)``, respectively, where
``K = min(M, N)``.
compute_uv : bool, optional
Whether or not to compute `u` and `vh` in addition to `s`. True
by default.
hermitian : bool, optional
If True, `a` is assumed to be Hermitian (symmetric if real-valued),
enabling a more efficient method for finding singular values.
Defaults to False.
.. versionadded:: 1.17.0
Returns
-------
When `compute_uv` is True, the result is a namedtuple with the following
attribute names:
U : { (..., M, M), (..., M, K) } array
Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
size as those of the input `a`. The size of the last two dimensions
depends on the value of `full_matrices`. Only returned when
`compute_uv` is True.
S : (..., K) array
Vector(s) with the singular values, within each vector sorted in
descending order. The first ``a.ndim - 2`` dimensions have the same
size as those of the input `a`.
Vh : { (..., N, N), (..., K, N) } array
Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
size as those of the input `a`. The size of the last two dimensions
depends on the value of `full_matrices`. Only returned when
`compute_uv` is True.
Raises
------
LinAlgError
If SVD computation does not converge.
See Also
--------
scipy.linalg.svd : Similar function in SciPy.
scipy.linalg.svdvals : Compute singular values of a matrix.
Notes
-----
.. versionchanged:: 1.8.0
Broadcasting rules apply, see the `numpy.linalg` documentation for
details.
The decomposition is performed using LAPACK routine ``_gesdd``.
SVD is usually described for the factorization of a 2D matrix :math:`A`.
The higher-dimensional case will be discussed below. In the 2D case, SVD is
written as :math:`A = U S V^H`, where :math:`A = a`, :math:`U= u`,
:math:`S= \mathtt{np.diag}(s)` and :math:`V^H = vh`. The 1D array `s`
contains the singular values of `a` and `u` and `vh` are unitary. The rows
of `vh` are the eigenvectors of :math:`A^H A` and the columns of `u` are
the eigenvectors of :math:`A A^H`. In both cases the corresponding
(possibly non-zero) eigenvalues are given by ``s**2``.
If `a` has more than two dimensions, then broadcasting rules apply, as
explained in :ref:`routines.linalg-broadcasting`. This means that SVD is
working in "stacked" mode: it iterates over all indices of the first
``a.ndim - 2`` dimensions and for each combination SVD is applied to the
last two indices. The matrix `a` can be reconstructed from the
decomposition with either ``(u * s[..., None, :]) @ vh`` or
``u @ (s[..., None] * vh)``. (The ``@`` operator can be replaced by the
function ``np.matmul`` for python versions below 3.5.)
If `a` is a ``matrix`` object (as opposed to an ``ndarray``), then so are
all the return values.
Examples
--------
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> a = rng.normal(size=(9, 6)) + 1j*rng.normal(size=(9, 6))
>>> b = rng.normal(size=(2, 7, 8, 3)) + 1j*rng.normal(size=(2, 7, 8, 3))
Reconstruction based on full SVD, 2D case:
>>> U, S, Vh = np.linalg.svd(a, full_matrices=True)
>>> U.shape, S.shape, Vh.shape
((9, 9), (6,), (6, 6))
>>> np.allclose(a, np.dot(U[:, :6] * S, Vh))
True
>>> smat = np.zeros((9, 6), dtype=complex)
>>> smat[:6, :6] = np.diag(S)
>>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
True
Reconstruction based on reduced SVD, 2D case:
>>> U, S, Vh = np.linalg.svd(a, full_matrices=False)
>>> U.shape, S.shape, Vh.shape
((9, 6), (6,), (6, 6))
>>> np.allclose(a, np.dot(U * S, Vh))
True
>>> smat = np.diag(S)
>>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
True
Reconstruction based on full SVD, 4D case:
>>> U, S, Vh = np.linalg.svd(b, full_matrices=True)
>>> U.shape, S.shape, Vh.shape
((2, 7, 8, 8), (2, 7, 3), (2, 7, 3, 3))
>>> np.allclose(b, np.matmul(U[..., :3] * S[..., None, :], Vh))
True
>>> np.allclose(b, np.matmul(U[..., :3], S[..., None] * Vh))
True
Reconstruction based on reduced SVD, 4D case:
>>> U, S, Vh = np.linalg.svd(b, full_matrices=False)
>>> U.shape, S.shape, Vh.shape
((2, 7, 8, 3), (2, 7, 3), (2, 7, 3, 3))
>>> np.allclose(b, np.matmul(U * S[..., None, :], Vh))
True
>>> np.allclose(b, np.matmul(U, S[..., None] * Vh))
True
svdvals(x, /)
Returns the singular values of a matrix (or a stack of matrices) ``x``.
When x is a stack of matrices, the function will compute the singular
values for each matrix in the stack.
This function is Array API compatible.
Calling ``np.svdvals(x)`` to get singular values is the same as
``np.svd(x, compute_uv=False, hermitian=False)``.
Parameters
----------
x : (..., M, N) array_like
Input array having shape (..., M, N) and whose last two
dimensions form matrices on which to perform singular value
decomposition. Should have a floating-point data type.
Returns
-------
out : ndarray
An array with shape (..., K) that contains the vector(s)
of singular values of length K, where K = min(M, N).
See Also
--------
scipy.linalg.svdvals : Compute singular values of a matrix.
Examples
--------
>>> np.linalg.svdvals([[1, 2, 3, 4, 5],
... [1, 4, 9, 16, 25],
... [1, 8, 27, 64, 125]])
array([146.68862757, 5.57510612, 0.60393245])
Determine the rank of a matrix using singular values:
>>> s = np.linalg.svdvals([[1, 2, 3],
... [2, 4, 6],
... [-1, 1, -1]]); s
array([8.38434191e+00, 1.64402274e+00, 2.31534378e-16])
>>> np.count_nonzero(s > 1e-10) # Matrix of rank 2
2
tensordot(x1, x2, /, *, axes=2)
Compute tensor dot product along specified axes.
Given two tensors, `a` and `b`, and an array_like object containing
two array_like objects, ``(a_axes, b_axes)``, sum the products of
`a`'s and `b`'s elements (components) over the axes specified by
``a_axes`` and ``b_axes``. The third argument can be a single non-negative
integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
of `a` and the first ``N`` dimensions of `b` are summed over.
Parameters
----------
a, b : array_like
Tensors to "dot".
axes : int or (2,) array_like
* integer_like
If an int N, sum over the last N axes of `a` and the first N axes
of `b` in order. The sizes of the corresponding axes must match.
* (2,) array_like
Or, a list of axes to be summed over, first sequence applying to `a`,
second to `b`. Both elements array_like must be of the same length.
Returns
-------
output : ndarray
The tensor dot product of the input.
See Also
--------
dot, einsum
Notes
-----
Three common use cases are:
* ``axes = 0`` : tensor product :math:`a\otimes b`
* ``axes = 1`` : tensor dot product :math:`a\cdot b`
* ``axes = 2`` : (default) tensor double contraction :math:`a:b`
When `axes` is a positive integer ``N``, the operation starts with
axis ``-N`` of `a` and axis ``0`` of `b`, and it continues through
axis ``-1`` of `a` and axis ``N-1`` of `b` (inclusive).
When there is more than one axis to sum over - and they are not the last
(first) axes of `a` (`b`) - the argument `axes` should consist of
two sequences of the same length, with the first axis to sum over given
first in both sequences, the second axis second, and so forth.
The shape of the result consists of the non-contracted axes of the
first tensor, followed by the non-contracted axes of the second.
Examples
--------
A "traditional" example:
>>> import numpy as np
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
>>> c.shape
(5, 2)
>>> c
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])
>>> # A slower but equivalent way of computing the same...
>>> d = np.zeros((5,2))
>>> for i in range(5):
... for j in range(2):
... for k in range(3):
... for n in range(4):
... d[i,j] += a[k,n,i] * b[n,k,j]
>>> c == d
array([[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True]])
An extended example taking advantage of the overloading of + and \*:
>>> a = np.array(range(1, 9))
>>> a.shape = (2, 2, 2)
>>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
>>> A.shape = (2, 2)
>>> a; A
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
array([['a', 'b'],
['c', 'd']], dtype=object)
>>> np.tensordot(a, A) # third argument default is 2 for double-contraction
array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
>>> np.tensordot(a, A, 1)
array([[['acc', 'bdd'],
['aaacccc', 'bbbdddd']],
[['aaaaacccccc', 'bbbbbdddddd'],
['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
>>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
array([[[[['a', 'b'],
['c', 'd']],
...
>>> np.tensordot(a, A, (0, 1))
array([[['abbbbb', 'cddddd'],
['aabbbbbb', 'ccdddddd']],
[['aaabbbbbbb', 'cccddddddd'],
['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
>>> np.tensordot(a, A, (2, 1))
array([[['abb', 'cdd'],
['aaabbbb', 'cccdddd']],
[['aaaaabbbbbb', 'cccccdddddd'],
['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
>>> np.tensordot(a, A, ((0, 1), (0, 1)))
array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
>>> np.tensordot(a, A, ((2, 1), (1, 0)))
array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
tensorinv(a, ind=2)
Compute the 'inverse' of an N-dimensional array.
The result is an inverse for `a` relative to the tensordot operation
``tensordot(a, b, ind)``, i. e., up to floating-point accuracy,
``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the
tensordot operation.
Parameters
----------
a : array_like
Tensor to 'invert'. Its shape must be 'square', i. e.,
``prod(a.shape[:ind]) == prod(a.shape[ind:])``.
ind : int, optional
Number of first indices that are involved in the inverse sum.
Must be a positive integer, default is 2.
Returns
-------
b : ndarray
`a`'s tensordot inverse, shape ``a.shape[ind:] + a.shape[:ind]``.
Raises
------
LinAlgError
If `a` is singular or not 'square' (in the above sense).
See Also
--------
numpy.tensordot, tensorsolve
Examples
--------
>>> import numpy as np
>>> a = np.eye(4*6)
>>> a.shape = (4, 6, 8, 3)
>>> ainv = np.linalg.tensorinv(a, ind=2)
>>> ainv.shape
(8, 3, 4, 6)
>>> rng = np.random.default_rng()
>>> b = rng.normal(size=(4, 6))
>>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b))
True
>>> a = np.eye(4*6)
>>> a.shape = (24, 8, 3)
>>> ainv = np.linalg.tensorinv(a, ind=1)
>>> ainv.shape
(8, 3, 24)
>>> rng = np.random.default_rng()
>>> b = rng.normal(size=24)
>>> np.allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
True
tensorsolve(a, b, axes=None)
Solve the tensor equation ``a x = b`` for x.
It is assumed that all indices of `x` are summed over in the product,
together with the rightmost indices of `a`, as is done in, for example,
``tensordot(a, x, axes=x.ndim)``.
Parameters
----------
a : array_like
Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals
the shape of that sub-tensor of `a` consisting of the appropriate
number of its rightmost indices, and must be such that
``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be
'square').
b : array_like
Right-hand tensor, which can be of any shape.
axes : tuple of ints, optional
Axes in `a` to reorder to the right, before inversion.
If None (default), no reordering is done.
Returns
-------
x : ndarray, shape Q
Raises
------
LinAlgError
If `a` is singular or not 'square' (in the above sense).
See Also
--------
numpy.tensordot, tensorinv, numpy.einsum
Examples
--------
>>> import numpy as np
>>> a = np.eye(2*3*4)
>>> a.shape = (2*3, 4, 2, 3, 4)
>>> rng = np.random.default_rng()
>>> b = rng.normal(size=(2*3, 4))
>>> x = np.linalg.tensorsolve(a, b)
>>> x.shape
(2, 3, 4)
>>> np.allclose(np.tensordot(a, x, axes=3), b)
True
trace(x, /, *, offset=0, dtype=None)
Returns the sum along the specified diagonals of a matrix
(or a stack of matrices) ``x``.
This function is Array API compatible, contrary to
:py:func:`numpy.trace`.
Parameters
----------
x : (...,M,N) array_like
Input array having shape (..., M, N) and whose innermost two
dimensions form MxN matrices.
offset : int, optional
Offset specifying the off-diagonal relative to the main diagonal,
where::
* offset = 0: the main diagonal.
* offset > 0: off-diagonal above the main diagonal.
* offset < 0: off-diagonal below the main diagonal.
dtype : dtype, optional
Data type of the returned array.
Returns
-------
out : ndarray
An array containing the traces and whose shape is determined by
removing the last two dimensions and storing the traces in the last
array dimension. For example, if x has rank k and shape:
(I, J, K, ..., L, M, N), then an output array has rank k-2 and shape:
(I, J, K, ..., L) where::
out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :])
The returned array must have a data type as described by the dtype
parameter above.
See Also
--------
numpy.trace
Examples
--------
>>> np.linalg.trace(np.eye(3))
3.0
>>> a = np.arange(8).reshape((2, 2, 2))
>>> np.linalg.trace(a)
array([3, 11])
Trace is computed with the last two axes as the 2-d sub-arrays.
This behavior differs from :py:func:`numpy.trace` which uses the first two
axes by default.
>>> a = np.arange(24).reshape((3, 2, 2, 2))
>>> np.linalg.trace(a).shape
(3, 2)
Traces adjacent to the main diagonal can be obtained by using the
`offset` argument:
>>> a = np.arange(9).reshape((3, 3)); a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.linalg.trace(a, offset=1) # First superdiagonal
6
>>> np.linalg.trace(a, offset=2) # Second superdiagonal
2
>>> np.linalg.trace(a, offset=-1) # First subdiagonal
10
>>> np.linalg.trace(a, offset=-2) # Second subdiagonal
6
vecdot(x1, x2, /, *, axis=-1)
Computes the vector dot product.
This function is restricted to arguments compatible with the Array API,
contrary to :func:`numpy.vecdot`.
Let :math:`\mathbf{a}` be a vector in ``x1`` and :math:`\mathbf{b}` be
a corresponding vector in ``x2``. The dot product is defined as:
.. math::
\mathbf{a} \cdot \mathbf{b} = \sum_{i=0}^{n-1} \overline{a_i}b_i
over the dimension specified by ``axis`` and where :math:`\overline{a_i}`
denotes the complex conjugate if :math:`a_i` is complex and the identity
otherwise.
Parameters
----------
x1 : array_like
First input array.
x2 : array_like
Second input array.
axis : int, optional
Axis over which to compute the dot product. Default: ``-1``.
Returns
-------
output : ndarray
The vector dot product of the input.
See Also
--------
numpy.vecdot
Examples
--------
Get the projected size along a given normal for an array of vectors.
>>> v = np.array([[0., 5., 0.], [0., 0., 10.], [0., 6., 8.]])
>>> n = np.array([0., 0.6, 0.8])
>>> np.linalg.vecdot(v, n)
array([ 3., 8., 10.])
vector_norm(x, /, *, axis=None, keepdims=False, ord=2)
Computes the vector norm of a vector (or batch of vectors) ``x``.
This function is Array API compatible.
Parameters
----------
x : array_like
Input array.
axis : {None, int, 2-tuple of ints}, optional
If an integer, ``axis`` specifies the axis (dimension) along which
to compute vector norms. If an n-tuple, ``axis`` specifies the axes
(dimensions) along which to compute batched vector norms. If ``None``,
the vector norm must be computed over all array values (i.e.,
equivalent to computing the vector norm of a flattened array).
Default: ``None``.
keepdims : bool, optional
If this is set to True, the axes which are normed over are left in
the result as dimensions with size one. Default: False.
ord : {1, -1, 2, -2, inf, -inf, 'fro', 'nuc'}, optional
The order of the norm. For details see the table under ``Notes``
in `numpy.linalg.norm`.
See Also
--------
numpy.linalg.norm : Generic norm function
Examples
--------
>>> from numpy import linalg as LA
>>> a = np.arange(9) + 1
>>> a
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = a.reshape((3, 3))
>>> b
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> LA.vector_norm(b)
16.881943016134134
>>> LA.vector_norm(b, ord=np.inf)
9.0
>>> LA.vector_norm(b, ord=-np.inf)
1.0
>>> LA.vector_norm(b, ord=1)
45.0
>>> LA.vector_norm(b, ord=-1)
0.3534857623790153
>>> LA.vector_norm(b, ord=2)
16.881943016134134
>>> LA.vector_norm(b, ord=-2)
0.8058837395885292
DATA
__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv',...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\linalg\__init__.py
numpy.linspace
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0, *, device=None)
Return evenly spaced numbers over a specified interval.
Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop`].
The endpoint of the interval can optionally be excluded.
.. versionchanged:: 1.16.0
Non-scalar `start` and `stop` are now supported.
.. versionchanged:: 1.20.0
Values are rounded towards ``-inf`` instead of ``0`` when an
integer ``dtype`` is specified. The old behavior can
still be obtained with ``np.linspace(start, stop, num).astype(int)``
Parameters
----------
start : array_like
The starting value of the sequence.
stop : array_like
The end value of the sequence, unless `endpoint` is set to False.
In that case, the sequence consists of all but the last of ``num + 1``
evenly spaced samples, so that `stop` is excluded. Note that the step
size changes when `endpoint` is False.
num : int, optional
Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
If True, `stop` is the last sample. Otherwise, it is not included.
Default is True.
retstep : bool, optional
If True, return (`samples`, `step`), where `step` is the spacing
between samples.
dtype : dtype, optional
The type of the output array. If `dtype` is not given, the data type
is inferred from `start` and `stop`. The inferred dtype will never be
an integer; `float` is chosen even if the arguments would produce an
array of integers.
.. versionadded:: 1.9.0
axis : int, optional
The axis in the result to store the samples. Relevant only if start
or stop are array-like. By default (0), the samples will be along a
new axis inserted at the beginning. Use -1 to get an axis at the end.
.. versionadded:: 1.16.0
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
samples : ndarray
There are `num` equally spaced samples in the closed interval
``[start, stop]`` or the half-open interval ``[start, stop)``
(depending on whether `endpoint` is True or False).
step : float, optional
Only returned if `retstep` is True
Size of spacing between samples.
See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the
number of samples).
geomspace : Similar to `linspace`, but with numbers spaced evenly on a log
scale (a geometric progression).
logspace : Similar to `geomspace`, but with the end points specified as
logarithms.
:ref:`how-to-partition`
Examples
--------
>>> import numpy as np
>>> np.linspace(2.0, 3.0, num=5)
array([2. , 2.25, 2.5 , 2.75, 3. ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([2. , 2.2, 2.4, 2.6, 2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
numpy.little_endian
Python Library Documentation: bool object class bool(int) | bool(x) -> bool | | Returns True when the argument x is true, False otherwise. | The builtins True and False are the only two instances of the class bool. | The class bool is a subclass of the class int, and cannot be subclassed. | | Method resolution order: | bool | int | object | | Methods defined here: | | __and__(self, value, /) | Return self&value. | | __invert__(self, /) | ~self | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __repr__(self, /) | Return repr(self). | | __ror__(self, value, /) | Return value|self. | | __rxor__(self, value, /) | Return value^self. | | __xor__(self, value, /) | Return self^value. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from int: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __ceil__(...) | Ceiling of an Integral returns itself. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floor__(...) | Flooring an Integral returns itself. | | __floordiv__(self, value, /) | Return self//value. | | __format__(self, format_spec, /) | Convert to a string according to format_spec. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __round__(...) | Rounding an Integral returns itself. | | Rounding with an ndigits argument also returns an integer. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __sizeof__(self, /) | Returns size in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __trunc__(...) | Truncating an Integral returns itself. | | as_integer_ratio(self, /) | Return a pair of integers, whose ratio is equal to the original int. | | The ratio is in lowest terms and has a positive denominator. | | >>> (10).as_integer_ratio() | (10, 1) | >>> (-10).as_integer_ratio() | (-10, 1) | >>> (0).as_integer_ratio() | (0, 1) | | bit_count(self, /) | Number of ones in the binary representation of the absolute value of self. | | Also known as the population count. | | >>> bin(13) | '0b1101' | >>> (13).bit_count() | 3 | | bit_length(self, /) | Number of bits necessary to represent self in binary. | | >>> bin(37) | '0b100101' | >>> (37).bit_length() | 6 | | conjugate(...) | Returns self, the complex conjugate of any int. | | is_integer(self, /) | Returns True. Exists for duck type compatibility with float.is_integer. | | to_bytes(self, /, length=1, byteorder='big', *, signed=False) | Return an array of bytes representing an integer. | | length | Length of bytes object to use. An OverflowError is raised if the | integer is not representable with the given number of bytes. Default | is length 1. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Determines whether two's complement is used to represent the integer. | If signed is False and a negative integer is given, an OverflowError | is raised. | | ---------------------------------------------------------------------- | Class methods inherited from int: | | from_bytes(bytes, byteorder='big', *, signed=False) | Return the integer represented by the given array of bytes. | | bytes | Holds the array of bytes to convert. The argument must either | support the buffer protocol or be an iterable object producing bytes. | Bytes and bytearray are examples of built-in objects that support the | buffer protocol. | byteorder | The byte order used to represent the integer. If byteorder is 'big', | the most significant byte is at the beginning of the byte array. If | byteorder is 'little', the most significant byte is at the end of the | byte array. To request the native byte order of the host system, use | `sys.byteorder' as the byte order value. Default is to use 'big'. | signed | Indicates whether two's complement is used to represent the integer. | | ---------------------------------------------------------------------- | Data descriptors inherited from int: | | denominator | the denominator of a rational number in lowest terms | | imag | the imaginary part of a complex number | | numerator | the numerator of a rational number in lowest terms | | real | the real part of a complex number
numpy.load
Python Library Documentation: function load in module numpy
load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII', *, max_header_size=10000)
Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.
.. warning:: Loading files that contain object arrays uses the ``pickle``
module, which is not secure against erroneous or maliciously
constructed data. Consider passing ``allow_pickle=False`` to
load data that is known not to contain object arrays for the
safer handling of untrusted sources.
Parameters
----------
file : file-like object, string, or pathlib.Path
The file to read. File-like objects must support the
``seek()`` and ``read()`` methods and must always
be opened in binary mode. Pickled files require that the
file-like object support the ``readline()`` method as well.
mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional
If not None, then memory-map the file, using the given mode (see
`numpy.memmap` for a detailed description of the modes). A
memory-mapped array is kept on disk. However, it can be accessed
and sliced like any ndarray. Memory mapping is especially useful
for accessing small fragments of large files without reading the
entire file into memory.
allow_pickle : bool, optional
Allow loading pickled object arrays stored in npy files. Reasons for
disallowing pickles include security, as loading pickled data can
execute arbitrary code. If pickles are disallowed, loading object
arrays will fail. Default: False
.. versionchanged:: 1.16.3
Made default False in response to CVE-2019-6446.
fix_imports : bool, optional
Only useful when loading Python 2 generated pickled files on Python 3,
which includes npy/npz files containing object arrays. If `fix_imports`
is True, pickle will try to map the old Python 2 names to the new names
used in Python 3.
encoding : str, optional
What encoding to use when reading Python 2 strings. Only useful when
loading Python 2 generated pickled files in Python 3, which includes
npy/npz files containing object arrays. Values other than 'latin1',
'ASCII', and 'bytes' are not allowed, as they can corrupt numerical
data. Default: 'ASCII'
max_header_size : int, optional
Maximum allowed size of the header. Large headers may not be safe
to load securely and thus require explicitly passing a larger value.
See :py:func:`ast.literal_eval()` for details.
This option is ignored when `allow_pickle` is passed. In that case
the file is by definition trusted and the limit is unnecessary.
Returns
-------
result : array, tuple, dict, etc.
Data stored in the file. For ``.npz`` files, the returned instance
of NpzFile class must be closed to avoid leaking file descriptors.
Raises
------
OSError
If the input file does not exist or cannot be read.
UnpicklingError
If ``allow_pickle=True``, but the file cannot be loaded as a pickle.
ValueError
The file contains an object array, but ``allow_pickle=False`` given.
EOFError
When calling ``np.load`` multiple times on the same file handle,
if all data has already been read
See Also
--------
save, savez, savez_compressed, loadtxt
memmap : Create a memory-map to an array stored in a file on disk.
lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file.
Notes
-----
- If the file contains pickle data, then whatever object is stored
in the pickle is returned.
- If the file is a ``.npy`` file, then a single array is returned.
- If the file is a ``.npz`` file, then a dictionary-like object is
returned, containing ``{filename: array}`` key-value pairs, one for
each file in the archive.
- If the file is a ``.npz`` file, the returned value supports the
context manager protocol in a similar fashion to the open function::
with load('foo.npz') as data:
a = data['a']
The underlying file descriptor is closed when exiting the 'with'
block.
Examples
--------
>>> import numpy as np
Store data to disk, and load it again:
>>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]]))
>>> np.load('/tmp/123.npy')
array([[1, 2, 3],
[4, 5, 6]])
Store compressed data to disk, and load it again:
>>> a=np.array([[1, 2, 3], [4, 5, 6]])
>>> b=np.array([1, 2])
>>> np.savez('/tmp/123.npz', a=a, b=b)
>>> data = np.load('/tmp/123.npz')
>>> data['a']
array([[1, 2, 3],
[4, 5, 6]])
>>> data['b']
array([1, 2])
>>> data.close()
Mem-map the stored array, and then access the second row
directly from disk:
>>> X = np.load('/tmp/123.npy', mmap_mode='r')
>>> X[1, :]
memmap([4, 5, 6])
numpy.loadtxt
Python Library Documentation: function loadtxt in module numpy
loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding=None, max_rows=None, *, quotechar=None, like=None)
Load data from a text file.
Parameters
----------
fname : file, str, pathlib.Path, list of str, generator
File, filename, list, or generator to read. If the filename
extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note
that generators must return bytes or strings. The strings
in a list or produced by a generator are treated as lines.
dtype : data-type, optional
Data-type of the resulting array; default: float. If this is a
structured data-type, the resulting array will be 1-dimensional, and
each row will be interpreted as an element of the array. In this
case, the number of columns used must match the number of fields in
the data-type.
comments : str or sequence of str or None, optional
The characters or list of characters used to indicate the start of a
comment. None implies no comments. For backwards compatibility, byte
strings will be decoded as 'latin1'. The default is '#'.
delimiter : str, optional
The character used to separate the values. For backwards compatibility,
byte strings will be decoded as 'latin1'. The default is whitespace.
.. versionchanged:: 1.23.0
Only single character delimiters are supported. Newline characters
cannot be used as the delimiter.
converters : dict or callable, optional
Converter functions to customize value parsing. If `converters` is
callable, the function is applied to all columns, else it must be a
dict that maps column number to a parser function.
See examples for further details.
Default: None.
.. versionchanged:: 1.23.0
The ability to pass a single callable to be applied to all columns
was added.
skiprows : int, optional
Skip the first `skiprows` lines, including comments; default: 0.
usecols : int or sequence, optional
Which columns to read, with 0 being the first. For example,
``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.
The default, None, results in all columns being read.
.. versionchanged:: 1.11.0
When a single column has to be read it is possible to use
an integer instead of a tuple. E.g ``usecols = 3`` reads the
fourth column the same way as ``usecols = (3,)`` would.
unpack : bool, optional
If True, the returned array is transposed, so that arguments may be
unpacked using ``x, y, z = loadtxt(...)``. When used with a
structured data-type, arrays are returned for each field.
Default is False.
ndmin : int, optional
The returned array will have at least `ndmin` dimensions.
Otherwise mono-dimensional axes will be squeezed.
Legal values: 0 (default), 1 or 2.
.. versionadded:: 1.6.0
encoding : str, optional
Encoding used to decode the inputfile. Does not apply to input streams.
The special value 'bytes' enables backward compatibility workarounds
that ensures you receive byte arrays as results if possible and passes
'latin1' encoded strings to converters. Override this value to receive
unicode arrays and pass strings as input to converters. If set to None
the system default is used. The default value is 'bytes'.
.. versionadded:: 1.14.0
.. versionchanged:: 2.0
Before NumPy 2, the default was ``'bytes'`` for Python 2
compatibility. The default is now ``None``.
max_rows : int, optional
Read `max_rows` rows of content after `skiprows` lines. The default is
to read all the rows. Note that empty rows containing no data such as
empty lines and comment lines are not counted towards `max_rows`,
while such lines are counted in `skiprows`.
.. versionadded:: 1.16.0
.. versionchanged:: 1.23.0
Lines containing no data, including comment lines (e.g., lines
starting with '#' or as specified via `comments`) are not counted
towards `max_rows`.
quotechar : unicode character or None, optional
The character used to denote the start and end of a quoted item.
Occurrences of the delimiter or comment characters are ignored within
a quoted item. The default value is ``quotechar=None``, which means
quoting support is disabled.
If two consecutive instances of `quotechar` are found within a quoted
field, the first is treated as an escape character. See examples.
.. versionadded:: 1.23.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
Data read from the text file.
See Also
--------
load, fromstring, fromregex
genfromtxt : Load data with missing values handled as specified.
scipy.io.loadmat : reads MATLAB data files
Notes
-----
This function aims to be a fast reader for simply formatted files. The
`genfromtxt` function provides more sophisticated handling of, e.g.,
lines with missing values.
Each row in the input text file must have the same number of values to be
able to read all values. If all rows do not have same number of values, a
subset of up to n columns (where n is the least number of values present
in all rows) can be read by specifying the columns via `usecols`.
.. versionadded:: 1.10.0
The strings produced by the Python float.hex method can be used as
input for floats.
Examples
--------
>>> import numpy as np
>>> from io import StringIO # StringIO behaves like a file object
>>> c = StringIO("0 1\n2 3")
>>> np.loadtxt(c)
array([[0., 1.],
[2., 3.]])
>>> d = StringIO("M 21 72\nF 35 58")
>>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
... 'formats': ('S1', 'i4', 'f4')})
array([(b'M', 21, 72.), (b'F', 35, 58.)],
dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')])
>>> c = StringIO("1,0,2\n3,0,4")
>>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
>>> x
array([1., 3.])
>>> y
array([2., 4.])
The `converters` argument is used to specify functions to preprocess the
text prior to parsing. `converters` can be a dictionary that maps
preprocessing functions to each column:
>>> s = StringIO("1.618, 2.296\n3.141, 4.669\n")
>>> conv = {
... 0: lambda x: np.floor(float(x)), # conversion fn for column 0
... 1: lambda x: np.ceil(float(x)), # conversion fn for column 1
... }
>>> np.loadtxt(s, delimiter=",", converters=conv)
array([[1., 3.],
[3., 5.]])
`converters` can be a callable instead of a dictionary, in which case it
is applied to all columns:
>>> s = StringIO("0xDE 0xAD\n0xC0 0xDE")
>>> import functools
>>> conv = functools.partial(int, base=16)
>>> np.loadtxt(s, converters=conv)
array([[222., 173.],
[192., 222.]])
This example shows how `converters` can be used to convert a field
with a trailing minus sign into a negative number.
>>> s = StringIO("10.01 31.25-\n19.22 64.31\n17.57- 63.94")
>>> def conv(fld):
... return -float(fld[:-1]) if fld.endswith("-") else float(fld)
...
>>> np.loadtxt(s, converters=conv)
array([[ 10.01, -31.25],
[ 19.22, 64.31],
[-17.57, 63.94]])
Using a callable as the converter can be particularly useful for handling
values with different formatting, e.g. floats with underscores:
>>> s = StringIO("1 2.7 100_000")
>>> np.loadtxt(s, converters=float)
array([1.e+00, 2.7e+00, 1.e+05])
This idea can be extended to automatically handle values specified in
many different formats, such as hex values:
>>> def conv(val):
... try:
... return float(val)
... except ValueError:
... return float.fromhex(val)
>>> s = StringIO("1, 2.5, 3_000, 0b4, 0x1.4000000000000p+2")
>>> np.loadtxt(s, delimiter=",", converters=conv)
array([1.0e+00, 2.5e+00, 3.0e+03, 1.8e+02, 5.0e+00])
Or a format where the ``-`` sign comes after the number:
>>> s = StringIO("10.01 31.25-\n19.22 64.31\n17.57- 63.94")
>>> conv = lambda x: -float(x[:-1]) if x.endswith("-") else float(x)
>>> np.loadtxt(s, converters=conv)
array([[ 10.01, -31.25],
[ 19.22, 64.31],
[-17.57, 63.94]])
Support for quoted fields is enabled with the `quotechar` parameter.
Comment and delimiter characters are ignored when they appear within a
quoted item delineated by `quotechar`:
>>> s = StringIO('"alpha, #42", 10.0\n"beta, #64", 2.0\n')
>>> dtype = np.dtype([("label", "U12"), ("value", float)])
>>> np.loadtxt(s, dtype=dtype, delimiter=",", quotechar='"')
array([('alpha, #42', 10.), ('beta, #64', 2.)],
dtype=[('label', '<U12'), ('value', '<f8')])
Quoted fields can be separated by multiple whitespace characters:
>>> s = StringIO('"alpha, #42" 10.0\n"beta, #64" 2.0\n')
>>> dtype = np.dtype([("label", "U12"), ("value", float)])
>>> np.loadtxt(s, dtype=dtype, delimiter=None, quotechar='"')
array([('alpha, #42', 10.), ('beta, #64', 2.)],
dtype=[('label', '<U12'), ('value', '<f8')])
Two consecutive quote characters within a quoted field are treated as a
single escaped character:
>>> s = StringIO('"Hello, my name is ""Monty""!"')
>>> np.loadtxt(s, dtype="U", delimiter=",", quotechar='"')
array('Hello, my name is "Monty"!', dtype='<U26')
Read subset of columns when all rows do not contain equal number of values:
>>> d = StringIO("1 2\n2 4\n3 9 12\n4 16 20")
>>> np.loadtxt(d, usecols=(0, 1))
array([[ 1., 2.],
[ 2., 4.],
[ 3., 9.],
[ 4., 16.]])
numpy.log
Python Library Documentation: ufunc
log = <ufunc 'log'>
log(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Natural logarithm, element-wise.
The natural logarithm `log` is the inverse of the exponential function,
so that `log(exp(x)) = x`. The natural logarithm is logarithm in base
`e`.
Parameters
----------
x : array_like
Input value.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The natural logarithm of `x`, element-wise.
This is a scalar if `x` is a scalar.
See Also
--------
log10, log2, log1p, emath.log
Notes
-----
Logarithm is a multivalued function: for each `x` there is an infinite
number of `z` such that `exp(z) = x`. The convention is to return the
`z` whose imaginary part lies in `(-pi, pi]`.
For real-valued input data types, `log` always returns real output. For
each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `log` is a complex analytical function that
has a branch cut `[-inf, 0]` and is continuous from above on it. `log`
handles the floating-point negative zero as an infinitesimal negative
number, conforming to the C99 standard.
In the cases where the input has a negative real part and a very small
negative complex part (approaching 0), the result is so close to `-pi`
that it evaluates to exactly `-pi`.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 67.
https://personal.math.ubc.ca/~cbm/aands/page_67.htm
.. [2] Wikipedia, "Logarithm". https://en.wikipedia.org/wiki/Logarithm
Examples
--------
>>> import numpy as np
>>> np.log([1, np.e, np.e**2, 0])
array([ 0., 1., 2., -inf])
numpy.log10
Python Library Documentation: ufunc
log10 = <ufunc 'log10'>
log10(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the base 10 logarithm of the input array, element-wise.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The logarithm to the base 10 of `x`, element-wise. NaNs are
returned where x is negative.
This is a scalar if `x` is a scalar.
See Also
--------
emath.log10
Notes
-----
Logarithm is a multivalued function: for each `x` there is an infinite
number of `z` such that `10**z = x`. The convention is to return the
`z` whose imaginary part lies in `(-pi, pi]`.
For real-valued input data types, `log10` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `log10` is a complex analytical function that
has a branch cut `[-inf, 0]` and is continuous from above on it.
`log10` handles the floating-point negative zero as an infinitesimal
negative number, conforming to the C99 standard.
In the cases where the input has a negative real part and a very small
negative complex part (approaching 0), the result is so close to `-pi`
that it evaluates to exactly `-pi`.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 67.
https://personal.math.ubc.ca/~cbm/aands/page_67.htm
.. [2] Wikipedia, "Logarithm". https://en.wikipedia.org/wiki/Logarithm
Examples
--------
>>> import numpy as np
>>> np.log10([1e-15, -3.])
array([-15., nan])
numpy.log1p
Python Library Documentation: ufunc
log1p = <ufunc 'log1p'>
log1p(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the natural logarithm of one plus the input array, element-wise.
Calculates ``log(1 + x)``.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Natural logarithm of `1 + x`, element-wise.
This is a scalar if `x` is a scalar.
See Also
--------
expm1 : ``exp(x) - 1``, the inverse of `log1p`.
Notes
-----
For real-valued input, `log1p` is accurate also for `x` so small
that `1 + x == 1` in floating-point accuracy.
Logarithm is a multivalued function: for each `x` there is an infinite
number of `z` such that `exp(z) = 1 + x`. The convention is to return
the `z` whose imaginary part lies in `[-pi, pi]`.
For real-valued input data types, `log1p` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `log1p` is a complex analytical function that
has a branch cut `[-inf, -1]` and is continuous from above on it.
`log1p` handles the floating-point negative zero as an infinitesimal
negative number, conforming to the C99 standard.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 67.
https://personal.math.ubc.ca/~cbm/aands/page_67.htm
.. [2] Wikipedia, "Logarithm". https://en.wikipedia.org/wiki/Logarithm
Examples
--------
>>> import numpy as np
>>> np.log1p(1e-99)
1e-99
>>> np.log(1 + 1e-99)
0.0
numpy.log2
Python Library Documentation: ufunc
log2 = <ufunc 'log2'>
log2(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Base-2 logarithm of `x`.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Base-2 logarithm of `x`.
This is a scalar if `x` is a scalar.
See Also
--------
log, log10, log1p, emath.log2
Notes
-----
.. versionadded:: 1.3.0
Logarithm is a multivalued function: for each `x` there is an infinite
number of `z` such that `2**z = x`. The convention is to return the `z`
whose imaginary part lies in `(-pi, pi]`.
For real-valued input data types, `log2` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `log2` is a complex analytical function that
has a branch cut `[-inf, 0]` and is continuous from above on it. `log2`
handles the floating-point negative zero as an infinitesimal negative
number, conforming to the C99 standard.
In the cases where the input has a negative real part and a very small
negative complex part (approaching 0), the result is so close to `-pi`
that it evaluates to exactly `-pi`.
Examples
--------
>>> import numpy as np
>>> x = np.array([0, 1, 2, 2**4])
>>> np.log2(x)
array([-inf, 0., 1., 4.])
>>> xi = np.array([0+1.j, 1, 2+0.j, 4.j])
>>> np.log2(xi)
array([ 0.+2.26618007j, 0.+0.j , 1.+0.j , 2.+2.26618007j])
numpy.logaddexp
Python Library Documentation: ufunc
logaddexp = <ufunc 'logaddexp'>
logaddexp(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Logarithm of the sum of exponentiations of the inputs.
Calculates ``log(exp(x1) + exp(x2))``. This function is useful in
statistics where the calculated probabilities of events may be so small
as to exceed the range of normal floating point numbers. In such cases
the logarithm of the calculated probability is stored. This function
allows adding probabilities stored in such a fashion.
Parameters
----------
x1, x2 : array_like
Input values.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
result : ndarray
Logarithm of ``exp(x1) + exp(x2)``.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logaddexp2: Logarithm of the sum of exponentiations of inputs in base 2.
Notes
-----
.. versionadded:: 1.3.0
Examples
--------
>>> import numpy as np
>>> prob1 = np.log(1e-50)
>>> prob2 = np.log(2.5e-50)
>>> prob12 = np.logaddexp(prob1, prob2)
>>> prob12
-113.87649168120691
>>> np.exp(prob12)
3.5000000000000057e-50
numpy.logaddexp2
Python Library Documentation: ufunc
logaddexp2 = <ufunc 'logaddexp2'>
logaddexp2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Logarithm of the sum of exponentiations of the inputs in base-2.
Calculates ``log2(2**x1 + 2**x2)``. This function is useful in machine
learning when the calculated probabilities of events may be so small as
to exceed the range of normal floating point numbers. In such cases
the base-2 logarithm of the calculated probability can be used instead.
This function allows adding probabilities stored in such a fashion.
Parameters
----------
x1, x2 : array_like
Input values.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
result : ndarray
Base-2 logarithm of ``2**x1 + 2**x2``.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logaddexp: Logarithm of the sum of exponentiations of the inputs.
Notes
-----
.. versionadded:: 1.3.0
Examples
--------
>>> import numpy as np
>>> prob1 = np.log2(1e-50)
>>> prob2 = np.log2(2.5e-50)
>>> prob12 = np.logaddexp2(prob1, prob2)
>>> prob1, prob2, prob12
(-166.09640474436813, -164.77447664948076, -164.28904982231052)
>>> 2**prob12
3.4999999999999914e-50
numpy.logical_and
Python Library Documentation: ufunc
logical_and = <ufunc 'logical_and'>
logical_and(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the truth value of x1 AND x2 element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or bool
Boolean result of the logical AND operation applied to the elements
of `x1` and `x2`; the shape is determined by broadcasting.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_or, logical_not, logical_xor
bitwise_and
Examples
--------
>>> import numpy as np
>>> np.logical_and(True, False)
False
>>> np.logical_and([True, False], [False, False])
array([False, False])
>>> x = np.arange(5)
>>> np.logical_and(x>1, x<4)
array([False, False, True, True, False])
The ``&`` operator can be used as a shorthand for ``np.logical_and`` on
boolean ndarrays.
>>> a = np.array([True, False])
>>> b = np.array([False, False])
>>> a & b
array([False, False])
numpy.logical_not
Python Library Documentation: ufunc
logical_not = <ufunc 'logical_not'>
logical_not(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the truth value of NOT x element-wise.
Parameters
----------
x : array_like
Logical NOT is applied to the elements of `x`.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : bool or ndarray of bool
Boolean result with the same shape as `x` of the NOT operation
on elements of `x`.
This is a scalar if `x` is a scalar.
See Also
--------
logical_and, logical_or, logical_xor
Examples
--------
>>> import numpy as np
>>> np.logical_not(3)
False
>>> np.logical_not([True, False, 0, 1])
array([False, True, True, False])
>>> x = np.arange(5)
>>> np.logical_not(x<3)
array([False, False, False, True, True])
numpy.logical_or
Python Library Documentation: ufunc
logical_or = <ufunc 'logical_or'>
logical_or(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the truth value of x1 OR x2 element-wise.
Parameters
----------
x1, x2 : array_like
Logical OR is applied to the elements of `x1` and `x2`.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or bool
Boolean result of the logical OR operation applied to the elements
of `x1` and `x2`; the shape is determined by broadcasting.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_and, logical_not, logical_xor
bitwise_or
Examples
--------
>>> import numpy as np
>>> np.logical_or(True, False)
True
>>> np.logical_or([True, False], [False, False])
array([ True, False])
>>> x = np.arange(5)
>>> np.logical_or(x < 1, x > 3)
array([ True, False, False, False, True])
The ``|`` operator can be used as a shorthand for ``np.logical_or`` on
boolean ndarrays.
>>> a = np.array([True, False])
>>> b = np.array([False, False])
>>> a | b
array([ True, False])
numpy.logical_xor
Python Library Documentation: ufunc
logical_xor = <ufunc 'logical_xor'>
logical_xor(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the truth value of x1 XOR x2, element-wise.
Parameters
----------
x1, x2 : array_like
Logical XOR is applied to the elements of `x1` and `x2`.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : bool or ndarray of bool
Boolean result of the logical XOR operation applied to the elements
of `x1` and `x2`; the shape is determined by broadcasting.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_and, logical_or, logical_not, bitwise_xor
Examples
--------
>>> import numpy as np
>>> np.logical_xor(True, False)
True
>>> np.logical_xor([True, True, False, False], [True, False, True, False])
array([False, True, True, False])
>>> x = np.arange(5)
>>> np.logical_xor(x < 1, x > 3)
array([ True, False, False, False, True])
Simple example showing support of broadcasting
>>> np.logical_xor(0, np.eye(2))
array([[ True, False],
[False, True]])
numpy.logspace
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)
Return numbers spaced evenly on a log scale.
In linear space, the sequence starts at ``base ** start``
(`base` to the power of `start`) and ends with ``base ** stop``
(see `endpoint` below).
.. versionchanged:: 1.16.0
Non-scalar `start` and `stop` are now supported.
.. versionchanged:: 1.25.0
Non-scalar 'base` is now supported
Parameters
----------
start : array_like
``base ** start`` is the starting value of the sequence.
stop : array_like
``base ** stop`` is the final value of the sequence, unless `endpoint`
is False. In that case, ``num + 1`` values are spaced over the
interval in log-space, of which all but the last (a sequence of
length `num`) are returned.
num : integer, optional
Number of samples to generate. Default is 50.
endpoint : boolean, optional
If true, `stop` is the last sample. Otherwise, it is not included.
Default is True.
base : array_like, optional
The base of the log space. The step size between the elements in
``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
Default is 10.0.
dtype : dtype
The type of the output array. If `dtype` is not given, the data type
is inferred from `start` and `stop`. The inferred type will never be
an integer; `float` is chosen even if the arguments would produce an
array of integers.
axis : int, optional
The axis in the result to store the samples. Relevant only if start,
stop, or base are array-like. By default (0), the samples will be
along a new axis inserted at the beginning. Use -1 to get an axis at
the end.
.. versionadded:: 1.16.0
Returns
-------
samples : ndarray
`num` samples, equally spaced on a log scale.
See Also
--------
arange : Similar to linspace, with the step size specified instead of the
number of samples. Note that, when used with a float endpoint, the
endpoint may or may not be included.
linspace : Similar to logspace, but with the samples uniformly distributed
in linear space, instead of log space.
geomspace : Similar to logspace, but with endpoints specified directly.
:ref:`how-to-partition`
Notes
-----
If base is a scalar, logspace is equivalent to the code
>>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
... # doctest: +SKIP
>>> power(base, y).astype(dtype)
... # doctest: +SKIP
Examples
--------
>>> import numpy as np
>>> np.logspace(2.0, 3.0, num=4)
array([ 100. , 215.443469 , 464.15888336, 1000. ])
>>> np.logspace(2.0, 3.0, num=4, endpoint=False)
array([100. , 177.827941 , 316.22776602, 562.34132519])
>>> np.logspace(2.0, 3.0, num=4, base=2.0)
array([4. , 5.0396842 , 6.34960421, 8. ])
>>> np.logspace(2.0, 3.0, num=4, base=[2.0, 3.0], axis=-1)
array([[ 4. , 5.0396842 , 6.34960421, 8. ],
[ 9. , 12.98024613, 18.72075441, 27. ]])
Graphical illustration:
>>> import matplotlib.pyplot as plt
>>> N = 10
>>> x1 = np.logspace(0.1, 1, N, endpoint=True)
>>> x2 = np.logspace(0.1, 1, N, endpoint=False)
>>> y = np.zeros(N)
>>> plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
numpy.long
Python Library Documentation: class int32 in module numpy class int32(signedinteger) | Method resolution order: | int32 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | int32.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.int32(127).bit_count() | 7 | >>> np.int32(-127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.longdouble
Python Library Documentation: class longdouble in module numpy class longdouble(floating) | Extended-precision floating-point number type, compatible with C | ``long double`` but not necessarily with IEEE 754 quadruple-precision. | | :Character code: ``'g'`` | | Method resolution order: | longdouble | floating | inexact | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | as_integer_ratio(...) | longdouble.as_integer_ratio() -> (int, int) | | Return a pair of integers, whose ratio is exactly equal to the original | floating point number, and with a positive denominator. | Raise `OverflowError` on infinities and a `ValueError` on NaNs. | | >>> np.longdouble(10.0).as_integer_ratio() | (10, 1) | >>> np.longdouble(0.0).as_integer_ratio() | (0, 1) | >>> np.longdouble(-.25).as_integer_ratio() | (-1, 4) | | is_integer(...) | longdouble.is_integer() -> bool | | Return ``True`` if the floating point number is finite with integral | value, and ``False`` otherwise. | | .. versionadded:: 1.22 | | Examples | -------- | >>> np.longdouble(-2.0).is_integer() | True | >>> np.longdouble(3.2).is_integer() | False | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from floating: | | __round__(...) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __reduce__(...) | Helper for pickle. | | __rlshift__(self, value, /) | Return value<<self. | | __ror__(self, value, /) | Return value|self. | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.longlong
Python Library Documentation: class int64 in module numpy class int64(signedinteger) | Default signed integer type, 64bit on 64bit systems and 32bit on 32bit | systems. | | :Character code: ``'q'`` | :Canonical name: `numpy.int_` | :Alias on this platform (win32 AMD64): `numpy.int64`: 64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``). | :Alias on this platform (win32 AMD64): `numpy.intp`: Signed integer large enough to fit pointer, compatible with C ``intptr_t``. | | Method resolution order: | int64 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | int64.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.int64(127).bit_count() | 7 | >>> np.int64(-127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.ma
Python Library Documentation: package numpy.ma in numpy
NAME
numpy.ma
DESCRIPTION
=============
Masked Arrays
=============
Arrays sometimes contain invalid or missing data. When doing operations
on such arrays, we wish to suppress invalid values, which is the purpose masked
arrays fulfill (an example of typical use is given below).
For example, examine the following array:
>>> x = np.array([2, 1, 3, np.nan, 5, 2, 3, np.nan])
When we try to calculate the mean of the data, the result is undetermined:
>>> np.mean(x)
nan
The mean is calculated using roughly ``np.sum(x)/len(x)``, but since
any number added to ``NaN`` [1]_ produces ``NaN``, this doesn't work. Enter
masked arrays:
>>> m = np.ma.masked_array(x, np.isnan(x))
>>> m
masked_array(data=[2.0, 1.0, 3.0, --, 5.0, 2.0, 3.0, --],
mask=[False, False, False, True, False, False, False, True],
fill_value=1e+20)
Here, we construct a masked array that suppress all ``NaN`` values. We
may now proceed to calculate the mean of the other values:
>>> np.mean(m)
2.6666666666666665
.. [1] Not-a-Number, a floating point value that is the result of an
invalid operation.
.. moduleauthor:: Pierre Gerard-Marchant
.. moduleauthor:: Jarrod Millman
PACKAGE CONTENTS
core
extras
mrecords
tests (package)
testutils
timer_comparison
CLASSES
builtins.Exception(builtins.BaseException)
numpy.ma.core.MAError
numpy.ma.core.MaskError
numpy.generic(builtins.object)
numpy.bool
numpy.ndarray(builtins.object)
MaskedArray
numpy.ma.core.mvoid
class MAError(builtins.Exception)
| Class for masked array related errors.
|
| Method resolution order:
| MAError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.Exception:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class MaskError(MAError)
| Class for mask related errors.
|
| Method resolution order:
| MaskError
| MAError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors inherited from MAError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.Exception:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
MaskType = class bool(generic)
| Boolean type (True or False), stored as a byte.
|
| .. warning::
|
| The :class:`bool` type is not a subclass of the :class:`int_` type
| (the :class:`bool` is not even a number type). This is different
| than Python's default implementation of :class:`bool` as a
| sub-class of :class:`int`.
|
| :Character code: ``'?'``
|
| Method resolution order:
| bool
| generic
| builtins.object
|
| Methods defined here:
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __rand__(self, value, /)
| Return value&self.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __str__(self, /)
| Return str(self).
|
| __xor__(self, value, /)
| Return self^value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| NumPy array scalar formatter
|
| __getitem__(self, key, /)
| Return self[key].
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| Helper for pickle.
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __setstate__(...)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| base
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.base`.
|
| data
| Pointer to start of data.
|
| device
|
| dtype
| Get array data-descriptor.
|
| flags
| The integer value of flags.
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
class MaskedArray(numpy.ndarray)
| MaskedArray(data=None, mask=np.False_, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None)
|
| An array class with possibly masked values.
|
| Masked values of True exclude the corresponding element from any
| computation.
|
| Construction::
|
| x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True,
| ndmin=0, fill_value=None, keep_mask=True, hard_mask=None,
| shrink=True, order=None)
|
| Parameters
| ----------
| data : array_like
| Input data.
| mask : sequence, optional
| Mask. Must be convertible to an array of booleans with the same
| shape as `data`. True indicates a masked (i.e. invalid) data.
| dtype : dtype, optional
| Data type of the output.
| If `dtype` is None, the type of the data argument (``data.dtype``)
| is used. If `dtype` is not None and different from ``data.dtype``,
| a copy is performed.
| copy : bool, optional
| Whether to copy the input data (True), or to use a reference instead.
| Default is False.
| subok : bool, optional
| Whether to return a subclass of `MaskedArray` if possible (True) or a
| plain `MaskedArray`. Default is True.
| ndmin : int, optional
| Minimum number of dimensions. Default is 0.
| fill_value : scalar, optional
| Value used to fill in the masked values when necessary.
| If None, a default based on the data-type is used.
| keep_mask : bool, optional
| Whether to combine `mask` with the mask of the input data, if any
| (True), or to use only `mask` for the output (False). Default is True.
| hard_mask : bool, optional
| Whether to use a hard mask or not. With a hard mask, masked values
| cannot be unmasked. Default is False.
| shrink : bool, optional
| Whether to force compression of an empty mask. Default is True.
| order : {'C', 'F', 'A'}, optional
| Specify the order of the array. If order is 'C', then the array
| will be in C-contiguous order (last-index varies the fastest).
| If order is 'F', then the returned array will be in
| Fortran-contiguous order (first-index varies the fastest).
| If order is 'A' (default), then the returned array may be
| in any order (either C-, Fortran-contiguous, or even discontiguous),
| unless a copy is required, in which case it will be C-contiguous.
|
| Examples
| --------
| >>> import numpy as np
|
| The ``mask`` can be initialized with an array of boolean values
| with the same shape as ``data``.
|
| >>> data = np.arange(6).reshape((2, 3))
| >>> np.ma.MaskedArray(data, mask=[[False, True, False],
| ... [False, False, True]])
| masked_array(
| data=[[0, --, 2],
| [3, 4, --]],
| mask=[[False, True, False],
| [False, False, True]],
| fill_value=999999)
|
| Alternatively, the ``mask`` can be initialized to homogeneous boolean
| array with the same shape as ``data`` by passing in a scalar
| boolean value:
|
| >>> np.ma.MaskedArray(data, mask=False)
| masked_array(
| data=[[0, 1, 2],
| [3, 4, 5]],
| mask=[[False, False, False],
| [False, False, False]],
| fill_value=999999)
|
| >>> np.ma.MaskedArray(data, mask=True)
| masked_array(
| data=[[--, --, --],
| [--, --, --]],
| mask=[[ True, True, True],
| [ True, True, True]],
| fill_value=999999,
| dtype=int64)
|
| .. note::
| The recommended practice for initializing ``mask`` with a scalar
| boolean value is to use ``True``/``False`` rather than
| ``np.True_``/``np.False_``. The reason is :attr:`nomask`
| is represented internally as ``np.False_``.
|
| >>> np.False_ is np.ma.nomask
| True
|
| Method resolution order:
| MaskedArray
| numpy.ndarray
| builtins.object
|
| Methods defined here:
|
| __add__(self, other) from numpy.ma.core.MaskedArray
| Add self to other, and return a new masked array.
|
| __array_finalize__(self, obj) from numpy.ma.core.MaskedArray
| Finalizes the masked array.
|
| __array_wrap__(self, obj, context=None, return_scalar=False) from numpy.ma.core.MaskedArray
| Special hook for ufuncs.
|
| Wraps the numpy array and sets the mask according to context.
|
| __deepcopy__(self, memo=None) from numpy.ma.core.MaskedArray
| a.__deepcopy__(memo, /)
|
| Used if :func:`copy.deepcopy` is called on an array.
|
| __div__(self, other) from numpy.ma.core.MaskedArray
| Divide other into self, and return a new masked array.
|
| __eq__(self, other) from numpy.ma.core.MaskedArray
| Check whether other equals self elementwise.
|
| When either of the elements is masked, the result is masked as well,
| but the underlying boolean data are still set, with self and other
| considered equal if both are masked, and unequal otherwise.
|
| For structured arrays, all fields are combined, with masked values
| ignored. The result is masked if all fields were masked, with self
| and other considered equal only if both were fully masked.
|
| __float__(self) from numpy.ma.core.MaskedArray
| Convert to float.
|
| __floordiv__(self, other) from numpy.ma.core.MaskedArray
| Divide other into self, and return a new masked array.
|
| __ge__(self, other) from numpy.ma.core.MaskedArray
| Return self>=value.
|
| __getitem__(self, indx) from numpy.ma.core.MaskedArray
| x.__getitem__(y) <==> x[y]
|
| Return the item described by i, as a masked array.
|
| __getstate__(self) from numpy.ma.core.MaskedArray
| Return the internal state of the masked array, for pickling
| purposes.
|
| __gt__(self, other) from numpy.ma.core.MaskedArray
| Return self>value.
|
| __iadd__(self, other) from numpy.ma.core.MaskedArray
| Add other to self in-place.
|
| __idiv__(self, other) from numpy.ma.core.MaskedArray
| Divide self by other in-place.
|
| __ifloordiv__(self, other) from numpy.ma.core.MaskedArray
| Floor divide self by other in-place.
|
| __imul__(self, other) from numpy.ma.core.MaskedArray
| Multiply self by other in-place.
|
| __int__(self) from numpy.ma.core.MaskedArray
| Convert to int.
|
| __ipow__(self, other) from numpy.ma.core.MaskedArray
| Raise self to the power other, in place.
|
| __isub__(self, other) from numpy.ma.core.MaskedArray
| Subtract other from self in-place.
|
| __itruediv__(self, other) from numpy.ma.core.MaskedArray
| True divide self by other in-place.
|
| __le__(self, other) from numpy.ma.core.MaskedArray
| Return self<=value.
|
| __lt__(self, other) from numpy.ma.core.MaskedArray
| Return self<value.
|
| __mul__(self, other) from numpy.ma.core.MaskedArray
| Multiply self by other, and return a new masked array.
|
| __ne__(self, other) from numpy.ma.core.MaskedArray
| Check whether other does not equal self elementwise.
|
| When either of the elements is masked, the result is masked as well,
| but the underlying boolean data are still set, with self and other
| considered equal if both are masked, and unequal otherwise.
|
| For structured arrays, all fields are combined, with masked values
| ignored. The result is masked if all fields were masked, with self
| and other considered equal only if both were fully masked.
|
| __pow__(self, other) from numpy.ma.core.MaskedArray
| Raise self to the power other, masking the potential NaNs/Infs
|
| __radd__(self, other) from numpy.ma.core.MaskedArray
| Add other to self, and return a new masked array.
|
| __reduce__(self) from numpy.ma.core.MaskedArray
| Return a 3-tuple for pickling a MaskedArray.
|
| __repr__(self) from numpy.ma.core.MaskedArray
| Literal string representation.
|
| __rfloordiv__(self, other) from numpy.ma.core.MaskedArray
| Divide self into other, and return a new masked array.
|
| __rmul__(self, other) from numpy.ma.core.MaskedArray
| Multiply other by self, and return a new masked array.
|
| __rpow__(self, other) from numpy.ma.core.MaskedArray
| Raise other to the power self, masking the potential NaNs/Infs
|
| __rsub__(self, other) from numpy.ma.core.MaskedArray
| Subtract self from other, and return a new masked array.
|
| __rtruediv__(self, other) from numpy.ma.core.MaskedArray
| Divide self into other, and return a new masked array.
|
| __setitem__(self, indx, value) from numpy.ma.core.MaskedArray
| x.__setitem__(i, y) <==> x[i]=y
|
| Set item described by index. If value is masked, masks those
| locations.
|
| __setmask__(self, mask, copy=False) from numpy.ma.core.MaskedArray
| Set the mask.
|
| __setstate__(self, state) from numpy.ma.core.MaskedArray
| Restore the internal state of the masked array, for
| pickling purposes. ``state`` is typically the output of the
| ``__getstate__`` output, and is a 5-tuple:
|
| - class name
| - a tuple giving the shape of the data
| - a typecode for the data
| - a binary string for the data
| - a binary string for the mask.
|
| __str__(self) from numpy.ma.core.MaskedArray
| Return str(self).
|
| __sub__(self, other) from numpy.ma.core.MaskedArray
| Subtract other from self, and return a new masked array.
|
| __truediv__(self, other) from numpy.ma.core.MaskedArray
| Divide other into self, and return a new masked array.
|
| all(self, axis=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns True if all elements evaluate to True.
|
| The output array is masked where all the values along the given axis
| are masked: if the output would have been a scalar and that all the
| values are masked, then the output is `masked`.
|
| Refer to `numpy.all` for full documentation.
|
| See Also
| --------
| numpy.ndarray.all : corresponding function for ndarrays
| numpy.all : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> np.ma.array([1,2,3]).all()
| True
| >>> a = np.ma.array([1,2,3], mask=True)
| >>> (a.all() is np.ma.masked)
| True
|
| anom(self, axis=None, dtype=None) from numpy.ma.core.MaskedArray
| Compute the anomalies (deviations from the arithmetic mean)
| along the given axis.
|
| Returns an array of anomalies, with the same shape as the input and
| where the arithmetic mean is computed along the given axis.
|
| Parameters
| ----------
| axis : int, optional
| Axis over which the anomalies are taken.
| The default is to use the mean of the flattened array as reference.
| dtype : dtype, optional
| Type to use in computing the variance. For arrays of integer type
| the default is float32; for arrays of float types it is the same as
| the array type.
|
| See Also
| --------
| mean : Compute the mean of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([1,2,3])
| >>> a.anom()
| masked_array(data=[-1., 0., 1.],
| mask=False,
| fill_value=1e+20)
|
| any(self, axis=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns True if any of the elements of `a` evaluate to True.
|
| Masked values are considered as False during computation.
|
| Refer to `numpy.any` for full documentation.
|
| See Also
| --------
| numpy.ndarray.any : corresponding function for ndarrays
| numpy.any : equivalent function
|
| argmax(self, axis=None, fill_value=None, out=None, *, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns array of indices of the maximum values along the given axis.
| Masked values are treated as if they had the value fill_value.
|
| Parameters
| ----------
| axis : {None, integer}
| If None, the index is into the flattened array, otherwise along
| the specified axis
| fill_value : scalar or None, optional
| Value used to fill in the masked values. If None, the output of
| maximum_fill_value(self._data) is used instead.
| out : {None, array}, optional
| Array into which the result can be placed. Its type is preserved
| and it must be of the right shape to hold the output.
|
| Returns
| -------
| index_array : {integer_array}
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.arange(6).reshape(2,3)
| >>> a.argmax()
| 5
| >>> a.argmax(0)
| array([1, 1, 1])
| >>> a.argmax(1)
| array([2, 2])
|
| argmin(self, axis=None, fill_value=None, out=None, *, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return array of indices to the minimum values along the given axis.
|
| Parameters
| ----------
| axis : {None, integer}
| If None, the index is into the flattened array, otherwise along
| the specified axis
| fill_value : scalar or None, optional
| Value used to fill in the masked values. If None, the output of
| minimum_fill_value(self._data) is used instead.
| out : {None, array}, optional
| Array into which the result can be placed. Its type is preserved
| and it must be of the right shape to hold the output.
|
| Returns
| -------
| ndarray or scalar
| If multi-dimension input, returns a new ndarray of indices to the
| minimum values along the given axis. Otherwise, returns a scalar
| of index to the minimum values along the given axis.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array(np.arange(4), mask=[1,1,0,0])
| >>> x.shape = (2,2)
| >>> x
| masked_array(
| data=[[--, --],
| [2, 3]],
| mask=[[ True, True],
| [False, False]],
| fill_value=999999)
| >>> x.argmin(axis=0, fill_value=-1)
| array([0, 0])
| >>> x.argmin(axis=0, fill_value=9)
| array([1, 1])
|
| argpartition(self, *args, **kwargs) from numpy.ma.core.MaskedArray
| a.argpartition(kth, axis=-1, kind='introselect', order=None)
|
| Returns the indices that would partition this array.
|
| Refer to `numpy.argpartition` for full documentation.
|
| .. versionadded:: 1.8.0
|
| See Also
| --------
| numpy.argpartition : equivalent function
|
| argsort(self, axis=<no value>, kind=None, order=None, endwith=True, fill_value=None, *, stable=False) from numpy.ma.core.MaskedArray
| Return an ndarray of indices that sort the array along the
| specified axis. Masked values are filled beforehand to
| `fill_value`.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which to sort. If None, the default, the flattened array
| is used.
|
| .. versionchanged:: 1.13.0
| Previously, the default was documented to be -1, but that was
| in error. At some future date, the default will change to -1, as
| originally intended.
| Until then, the axis should be given explicitly when
| ``arr.ndim > 1``, to avoid a FutureWarning.
| kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| The sorting algorithm used.
| order : list, optional
| When `a` is an array with fields defined, this argument specifies
| which fields to compare first, second, etc. Not all fields need be
| specified.
| endwith : {True, False}, optional
| Whether missing values (if any) should be treated as the largest values
| (True) or the smallest values (False)
| When the array contains unmasked values at the same extremes of the
| datatype, the ordering of these values and the masked values is
| undefined.
| fill_value : scalar or None, optional
| Value used internally for the masked values.
| If ``fill_value`` is not None, it supersedes ``endwith``.
| stable : bool, optional
| Only for compatibility with ``np.argsort``. Ignored.
|
| Returns
| -------
| index_array : ndarray, int
| Array of indices that sort `a` along the specified axis.
| In other words, ``a[index_array]`` yields a sorted `a`.
|
| See Also
| --------
| ma.MaskedArray.sort : Describes sorting algorithms used.
| lexsort : Indirect stable sort with multiple keys.
| numpy.ndarray.sort : Inplace sort.
|
| Notes
| -----
| See `sort` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([3,2,1], mask=[False, False, True])
| >>> a
| masked_array(data=[3, 2, --],
| mask=[False, False, True],
| fill_value=999999)
| >>> a.argsort()
| array([1, 0, 2])
|
| compress(self, condition, axis=None, out=None) from numpy.ma.core.MaskedArray
| Return `a` where condition is ``True``.
|
| If condition is a `~ma.MaskedArray`, missing values are considered
| as ``False``.
|
| Parameters
| ----------
| condition : var
| Boolean 1-d array selecting which entries to return. If len(condition)
| is less than the size of a along the axis, then output is truncated
| to length of condition array.
| axis : {None, int}, optional
| Axis along which the operation must be performed.
| out : {None, ndarray}, optional
| Alternative output array in which to place the result. It must have
| the same shape as the expected output but the type will be cast if
| necessary.
|
| Returns
| -------
| result : MaskedArray
| A :class:`~ma.MaskedArray` object.
|
| Notes
| -----
| Please note the difference with :meth:`compressed` !
| The output of :meth:`compress` has a mask, the output of
| :meth:`compressed` does not.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.compress([1, 0, 1])
| masked_array(data=[1, 3],
| mask=[False, False],
| fill_value=999999)
|
| >>> x.compress([1, 0, 1], axis=1)
| masked_array(
| data=[[1, 3],
| [--, --],
| [7, 9]],
| mask=[[False, False],
| [ True, True],
| [False, False]],
| fill_value=999999)
|
| compressed(self) from numpy.ma.core.MaskedArray
| Return all the non-masked data as a 1-D array.
|
| Returns
| -------
| data : ndarray
| A new `ndarray` holding the non-masked data is returned.
|
| Notes
| -----
| The result is **not** a MaskedArray!
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3)
| >>> x.compressed()
| array([0, 1])
| >>> type(x.compressed())
| <class 'numpy.ndarray'>
|
| N-D arrays are compressed to 1-D.
|
| >>> arr = [[1, 2], [3, 4]]
| >>> mask = [[1, 0], [0, 1]]
| >>> x = np.ma.array(arr, mask=mask)
| >>> x.compressed()
| array([2, 3])
|
| copy(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.copy(order='C')
|
| Return a copy of the array.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout of the copy. 'C' means C-order,
| 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| 'C' otherwise. 'K' means match the layout of `a` as closely
| as possible. (Note that this function and :func:`numpy.copy` are very
| similar but have different default values for their order=
| arguments, and this function always passes sub-classes through.)
|
| See also
| --------
| numpy.copy : Similar function with different default behavior
| numpy.copyto
|
| Notes
| -----
| This function is the preferred method for creating an array copy. The
| function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| and will not pass sub-classes through by default.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[1,2,3],[4,5,6]], order='F')
|
| >>> y = x.copy()
|
| >>> x.fill(0)
|
| >>> x
| array([[0, 0, 0],
| [0, 0, 0]])
|
| >>> y
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> y.flags['C_CONTIGUOUS']
| True
|
| For arrays containing Python objects (e.g. dtype=object),
| the copy is a shallow one. The new array will contain the
| same object which may lead to surprises if that object can
| be modified (is mutable):
|
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> b = a.copy()
| >>> b[2][0] = 10
| >>> a
| array([1, 'm', list([10, 3, 4])], dtype=object)
|
| To ensure all elements within an ``object`` array are copied,
| use `copy.deepcopy`:
|
| >>> import copy
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> c = copy.deepcopy(a)
| >>> c[2][0] = 10
| >>> c
| array([1, 'm', list([10, 3, 4])], dtype=object)
| >>> a
| array([1, 'm', list([2, 3, 4])], dtype=object)
|
| count(self, axis=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Count the non-masked elements of the array along the given axis.
|
| Parameters
| ----------
| axis : None or int or tuple of ints, optional
| Axis or axes along which the count is performed.
| The default, None, performs the count over all
| the dimensions of the input array. `axis` may be negative, in
| which case it counts from the last to the first axis.
|
| .. versionadded:: 1.10.0
|
| If this is a tuple of ints, the count is performed on multiple
| axes, instead of a single axis or all the axes as before.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| result : ndarray or scalar
| An array with the same shape as the input array, with the specified
| axis removed. If the array is a 0-d array, or if `axis` is None, a
| scalar is returned.
|
| See Also
| --------
| ma.count_masked : Count masked elements in array or along a given axis.
|
| Examples
| --------
| >>> import numpy.ma as ma
| >>> a = ma.arange(6).reshape((2, 3))
| >>> a[1, :] = ma.masked
| >>> a
| masked_array(
| data=[[0, 1, 2],
| [--, --, --]],
| mask=[[False, False, False],
| [ True, True, True]],
| fill_value=999999)
| >>> a.count()
| 3
|
| When the `axis` keyword is specified an array of appropriate size is
| returned.
|
| >>> a.count(axis=0)
| array([1, 1, 1])
| >>> a.count(axis=1)
| array([3, 0])
|
| cumprod(self, axis=None, dtype=None, out=None) from numpy.ma.core.MaskedArray
| Return the cumulative product of the array elements over the given axis.
|
| Masked values are set to 1 internally during the computation.
| However, their position is saved, and the result will be masked at
| the same locations.
|
| Refer to `numpy.cumprod` for full documentation.
|
| Notes
| -----
| The mask is lost if `out` is not a valid MaskedArray !
|
| Arithmetic is modular when using integer types, and no error is
| raised on overflow.
|
| See Also
| --------
| numpy.ndarray.cumprod : corresponding function for ndarrays
| numpy.cumprod : equivalent function
|
| cumsum(self, axis=None, dtype=None, out=None) from numpy.ma.core.MaskedArray
| Return the cumulative sum of the array elements over the given axis.
|
| Masked values are set to 0 internally during the computation.
| However, their position is saved, and the result will be masked at
| the same locations.
|
| Refer to `numpy.cumsum` for full documentation.
|
| Notes
| -----
| The mask is lost if `out` is not a valid :class:`ma.MaskedArray` !
|
| Arithmetic is modular when using integer types, and no error is
| raised on overflow.
|
| See Also
| --------
| numpy.ndarray.cumsum : corresponding function for ndarrays
| numpy.cumsum : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
| >>> marr.cumsum()
| masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33],
| mask=[False, False, False, True, True, True, False, False,
| False, False],
| fill_value=999999)
|
| diagonal(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.diagonal(offset=0, axis1=0, axis2=1)
|
| Return specified diagonals. In NumPy 1.9 the returned array is a
| read-only view instead of a copy as in previous NumPy versions. In
| a future version the read-only restriction will be removed.
|
| Refer to :func:`numpy.diagonal` for full documentation.
|
| See Also
| --------
| numpy.diagonal : equivalent function
|
| dot(self, b, out=None, strict=False) from numpy.ma.core.MaskedArray
| a.dot(b, out=None)
|
| Masked dot product of two arrays. Note that `out` and `strict` are
| located in different positions than in `ma.dot`. In order to
| maintain compatibility with the functional version, it is
| recommended that the optional arguments be treated as keyword only.
| At some point that may be mandatory.
|
| .. versionadded:: 1.10.0
|
| Parameters
| ----------
| b : masked_array_like
| Inputs array.
| out : masked_array, optional
| Output argument. This must have the exact kind that would be
| returned if it was not used. In particular, it must have the
| right type, must be C-contiguous, and its dtype must be the
| dtype that would be returned for `ma.dot(a,b)`. This is a
| performance feature. Therefore, if these conditions are not
| met, an exception is raised, instead of attempting to be
| flexible.
| strict : bool, optional
| Whether masked data are propagated (True) or set to 0 (False)
| for the computation. Default is False. Propagating the mask
| means that if a masked value appears in a row or column, the
| whole row or column is considered masked.
|
| .. versionadded:: 1.10.2
|
| See Also
| --------
| numpy.ma.dot : equivalent function
|
| filled(self, fill_value=None) from numpy.ma.core.MaskedArray
| Return a copy of self, with masked values filled with a given value.
| **However**, if there are no masked values to fill, self will be
| returned instead as an ndarray.
|
| Parameters
| ----------
| fill_value : array_like, optional
| The value to use for invalid entries. Can be scalar or non-scalar.
| If non-scalar, the resulting ndarray must be broadcastable over
| input array. Default is None, in which case, the `fill_value`
| attribute of the array is used instead.
|
| Returns
| -------
| filled_array : ndarray
| A copy of ``self`` with invalid entries replaced by *fill_value*
| (be it the function argument or the attribute of ``self``), or
| ``self`` itself as an ndarray if there are no invalid entries to
| be replaced.
|
| Notes
| -----
| The result is **not** a MaskedArray!
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
| >>> x.filled()
| array([ 1, 2, -999, 4, -999])
| >>> x.filled(fill_value=1000)
| array([ 1, 2, 1000, 4, 1000])
| >>> type(x.filled())
| <class 'numpy.ndarray'>
|
| Subclassing is preserved. This means that if, e.g., the data part of
| the masked array is a recarray, `filled` returns a recarray:
|
| >>> x = np.array([(-1, 2), (-3, 4)], dtype='i8,i8').view(np.recarray)
| >>> m = np.ma.array(x, mask=[(True, False), (False, True)])
| >>> m.filled()
| rec.array([(999999, 2), ( -3, 999999)],
| dtype=[('f0', '<i8'), ('f1', '<i8')])
|
| flatten(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.flatten(order='C')
|
| Return a copy of the array collapsed into one dimension.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| 'C' means to flatten in row-major (C-style) order.
| 'F' means to flatten in column-major (Fortran-
| style) order. 'A' means to flatten in column-major
| order if `a` is Fortran *contiguous* in memory,
| row-major order otherwise. 'K' means to flatten
| `a` in the order the elements occur in memory.
| The default is 'C'.
|
| Returns
| -------
| y : ndarray
| A copy of the input array, flattened to one dimension.
|
| See Also
| --------
| ravel : Return a flattened array.
| flat : A 1-D flat iterator over the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,2], [3,4]])
| >>> a.flatten()
| array([1, 2, 3, 4])
| >>> a.flatten('F')
| array([1, 3, 2, 4])
|
| get_fill_value = fill_value(self) from numpy.ma.core.MaskedArray
| The filling value of the masked array is a scalar. When setting, None
| will set to a default based on the data type.
|
| Examples
| --------
| >>> import numpy as np
| >>> for dt in [np.int32, np.int64, np.float64, np.complex128]:
| ... np.ma.array([0, 1], dtype=dt).get_fill_value()
| ...
| np.int64(999999)
| np.int64(999999)
| np.float64(1e+20)
| np.complex128(1e+20+0j)
|
| >>> x = np.ma.array([0, 1.], fill_value=-np.inf)
| >>> x.fill_value
| np.float64(-inf)
| >>> x.fill_value = np.pi
| >>> x.fill_value
| np.float64(3.1415926535897931)
|
| Reset to default:
|
| >>> x.fill_value = None
| >>> x.fill_value
| np.float64(1e+20)
|
| get_imag = imag(self) from numpy.ma.core.MaskedArray
| The imaginary part of the masked array.
|
| This property is a view on the imaginary part of this `MaskedArray`.
|
| See Also
| --------
| real
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.imag
| masked_array(data=[1.0, --, 1.6],
| mask=[False, True, False],
| fill_value=1e+20)
|
| get_real = real(self) from numpy.ma.core.MaskedArray
| The real part of the masked array.
|
| This property is a view on the real part of this `MaskedArray`.
|
| See Also
| --------
| imag
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.real
| masked_array(data=[1.0, --, 3.45],
| mask=[False, True, False],
| fill_value=1e+20)
|
| harden_mask(self) from numpy.ma.core.MaskedArray
| Force the mask to hard, preventing unmasking by assignment.
|
| Whether the mask of a masked array is hard or soft is determined by
| its `~ma.MaskedArray.hardmask` property. `harden_mask` sets
| `~ma.MaskedArray.hardmask` to ``True`` (and returns the modified
| self).
|
| See Also
| --------
| ma.MaskedArray.hardmask
| ma.MaskedArray.soften_mask
|
| ids(self) from numpy.ma.core.MaskedArray
| Return the addresses of the data and mask areas.
|
| Parameters
| ----------
| None
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1])
| >>> x.ids()
| (166670640, 166659832) # may vary
|
| If the array has no mask, the address of `nomask` is returned. This address
| is typically not close to the data in memory:
|
| >>> x = np.ma.array([1, 2, 3])
| >>> x.ids()
| (166691080, 3083169284) # may vary
|
| iscontiguous(self) from numpy.ma.core.MaskedArray
| Return a boolean indicating whether the data is contiguous.
|
| Parameters
| ----------
| None
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1, 2, 3])
| >>> x.iscontiguous()
| True
|
| `iscontiguous` returns one of the flags of the masked array:
|
| >>> x.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : True
| OWNDATA : False
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
|
| max(self, axis=None, out=None, fill_value=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the maximum along a given axis.
|
| Parameters
| ----------
| axis : None or int or tuple of ints, optional
| Axis along which to operate. By default, ``axis`` is None and the
| flattened input is used.
| .. versionadded:: 1.7.0
| If this is a tuple of ints, the maximum is selected over multiple
| axes, instead of a single axis or all the axes as before.
| out : array_like, optional
| Alternative output array in which to place the result. Must
| be of the same shape and buffer length as the expected output.
| fill_value : scalar or None, optional
| Value used to fill in the masked values.
| If None, use the output of maximum_fill_value().
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| amax : array_like
| New array holding the result.
| If ``out`` was specified, ``out`` is returned.
|
| See Also
| --------
| ma.maximum_fill_value
| Returns the maximum filling value for a given datatype.
|
| Examples
| --------
| >>> import numpy.ma as ma
| >>> x = [[-1., 2.5], [4., -2.], [3., 0.]]
| >>> mask = [[0, 0], [1, 0], [1, 0]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> masked_x
| masked_array(
| data=[[-1.0, 2.5],
| [--, -2.0],
| [--, 0.0]],
| mask=[[False, False],
| [ True, False],
| [ True, False]],
| fill_value=1e+20)
| >>> ma.max(masked_x)
| 2.5
| >>> ma.max(masked_x, axis=0)
| masked_array(data=[-1.0, 2.5],
| mask=[False, False],
| fill_value=1e+20)
| >>> ma.max(masked_x, axis=1, keepdims=True)
| masked_array(
| data=[[2.5],
| [-2.0],
| [0.0]],
| mask=[[False],
| [False],
| [False]],
| fill_value=1e+20)
| >>> mask = [[1, 1], [1, 1], [1, 1]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> ma.max(masked_x, axis=1)
| masked_array(data=[--, --, --],
| mask=[ True, True, True],
| fill_value=1e+20,
| dtype=float64)
|
| mean(self, axis=None, dtype=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns the average of the array elements along given axis.
|
| Masked entries are ignored, and result elements which are not
| finite will be masked.
|
| Refer to `numpy.mean` for full documentation.
|
| See Also
| --------
| numpy.ndarray.mean : corresponding function for ndarrays
| numpy.mean : Equivalent function
| numpy.ma.average : Weighted average.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([1,2,3], mask=[False, False, True])
| >>> a
| masked_array(data=[1, 2, --],
| mask=[False, False, True],
| fill_value=999999)
| >>> a.mean()
| 1.5
|
| min(self, axis=None, out=None, fill_value=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the minimum along a given axis.
|
| Parameters
| ----------
| axis : None or int or tuple of ints, optional
| Axis along which to operate. By default, ``axis`` is None and the
| flattened input is used.
| .. versionadded:: 1.7.0
| If this is a tuple of ints, the minimum is selected over multiple
| axes, instead of a single axis or all the axes as before.
| out : array_like, optional
| Alternative output array in which to place the result. Must be of
| the same shape and buffer length as the expected output.
| fill_value : scalar or None, optional
| Value used to fill in the masked values.
| If None, use the output of `minimum_fill_value`.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| amin : array_like
| New array holding the result.
| If ``out`` was specified, ``out`` is returned.
|
| See Also
| --------
| ma.minimum_fill_value
| Returns the minimum filling value for a given datatype.
|
| Examples
| --------
| >>> import numpy.ma as ma
| >>> x = [[1., -2., 3.], [0.2, -0.7, 0.1]]
| >>> mask = [[1, 1, 0], [0, 0, 1]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> masked_x
| masked_array(
| data=[[--, --, 3.0],
| [0.2, -0.7, --]],
| mask=[[ True, True, False],
| [False, False, True]],
| fill_value=1e+20)
| >>> ma.min(masked_x)
| -0.7
| >>> ma.min(masked_x, axis=-1)
| masked_array(data=[3.0, -0.7],
| mask=[False, False],
| fill_value=1e+20)
| >>> ma.min(masked_x, axis=0, keepdims=True)
| masked_array(data=[[0.2, -0.7, 3.0]],
| mask=[[False, False, False]],
| fill_value=1e+20)
| >>> mask = [[1, 1, 1,], [1, 1, 1]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> ma.min(masked_x, axis=0)
| masked_array(data=[--, --, --],
| mask=[ True, True, True],
| fill_value=1e+20,
| dtype=float64)
|
| nonzero(self) from numpy.ma.core.MaskedArray
| Return the indices of unmasked elements that are not zero.
|
| Returns a tuple of arrays, one for each dimension, containing the
| indices of the non-zero elements in that dimension. The corresponding
| non-zero values can be obtained with::
|
| a[a.nonzero()]
|
| To group the indices by element, rather than dimension, use
| instead::
|
| np.transpose(a.nonzero())
|
| The result of this is always a 2d array, with a row for each non-zero
| element.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| tuple_of_arrays : tuple
| Indices of elements that are non-zero.
|
| See Also
| --------
| numpy.nonzero :
| Function operating on ndarrays.
| flatnonzero :
| Return indices that are non-zero in the flattened version of the input
| array.
| numpy.ndarray.nonzero :
| Equivalent ndarray method.
| count_nonzero :
| Counts the number of non-zero elements in the input array.
|
| Examples
| --------
| >>> import numpy as np
| >>> import numpy.ma as ma
| >>> x = ma.array(np.eye(3))
| >>> x
| masked_array(
| data=[[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]],
| mask=False,
| fill_value=1e+20)
| >>> x.nonzero()
| (array([0, 1, 2]), array([0, 1, 2]))
|
| Masked elements are ignored.
|
| >>> x[1, 1] = ma.masked
| >>> x
| masked_array(
| data=[[1.0, 0.0, 0.0],
| [0.0, --, 0.0],
| [0.0, 0.0, 1.0]],
| mask=[[False, False, False],
| [False, True, False],
| [False, False, False]],
| fill_value=1e+20)
| >>> x.nonzero()
| (array([0, 2]), array([0, 2]))
|
| Indices can also be grouped by element.
|
| >>> np.transpose(x.nonzero())
| array([[0, 0],
| [2, 2]])
|
| 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, ma.nonzero(a > 3)
| yields the indices of the `a` where the condition is true.
|
| >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
| >>> a > 3
| masked_array(
| data=[[False, False, False],
| [ True, True, True],
| [ True, True, True]],
| mask=False,
| fill_value=True)
| >>> ma.nonzero(a > 3)
| (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
|
| The ``nonzero`` method of the condition array can also be called.
|
| >>> (a > 3).nonzero()
| (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
|
| partition(self, *args, **kwargs) from numpy.ma.core.MaskedArray
| a.partition(kth, axis=-1, kind='introselect', order=None)
|
| Partially sorts the elements in the array 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. In the output array, all elements smaller than the k-th element
| are located to the left of this element and all equal or greater are
| located to its right. The ordering of the elements in the two partitions
| on the either side of the k-th element in the output array is undefined.
|
| .. versionadded:: 1.8.0
|
| Parameters
| ----------
| kth : int or sequence of ints
| Element index to partition by. The kth element value 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 kth it will partition all elements
| indexed by kth of them into their sorted position at once.
|
| .. deprecated:: 1.22.0
| Passing booleans as index is deprecated.
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'introselect'}, optional
| Selection algorithm. Default is 'introselect'.
| order : str 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, and not all fields need to be specified,
| but unspecified fields will still be used, in the order in which
| they come up in the dtype, to break ties.
|
| See Also
| --------
| numpy.partition : Return a partitioned copy of an array.
| argpartition : Indirect partition.
| sort : Full sort.
|
| Notes
| -----
| See ``np.partition`` for notes on the different algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([3, 4, 2, 1])
| >>> a.partition(3)
| >>> a
| array([2, 1, 3, 4]) # may vary
|
| >>> a.partition((1, 3))
| >>> a
| array([1, 2, 3, 4])
|
| prod(self, axis=None, dtype=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the product of the array elements over the given axis.
|
| Masked elements are set to 1 internally for computation.
|
| Refer to `numpy.prod` for full documentation.
|
| Notes
| -----
| Arithmetic is modular when using integer types, and no error is raised
| on overflow.
|
| See Also
| --------
| numpy.ndarray.prod : corresponding function for ndarrays
| numpy.prod : equivalent function
|
| product = prod(self, axis=None, dtype=None, out=None, keepdims=<no value>)
|
| ptp(self, axis=None, out=None, fill_value=None, keepdims=False) from numpy.ma.core.MaskedArray
| Return (maximum - minimum) along the given dimension
| (i.e. peak-to-peak value).
|
| .. warning::
| `ptp` preserves the data type of the array. This means the
| return value for an input of signed integers with n bits
| (e.g. `np.int8`, `np.int16`, etc) is also a signed integer
| with n bits. In that case, peak-to-peak values greater than
| ``2**(n-1)-1`` will be returned as negative values. An example
| with a work-around is shown below.
|
| Parameters
| ----------
| axis : {None, int}, optional
| Axis along which to find the peaks. If None (default) the
| flattened array is used.
| out : {None, array_like}, optional
| Alternative output array in which to place the result. It must
| have the same shape and buffer length as the expected output
| but the type will be cast if necessary.
| fill_value : scalar or None, optional
| Value used to fill in the masked values.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| ptp : ndarray.
| A new array holding the result, unless ``out`` was
| specified, in which case a reference to ``out`` is returned.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.MaskedArray([[4, 9, 2, 10],
| ... [6, 9, 7, 12]])
|
| >>> x.ptp(axis=1)
| masked_array(data=[8, 6],
| mask=False,
| fill_value=999999)
|
| >>> x.ptp(axis=0)
| masked_array(data=[2, 0, 5, 2],
| mask=False,
| fill_value=999999)
|
| >>> x.ptp()
| 10
|
| This example shows that a negative value can be returned when
| the input is an array of signed integers.
|
| >>> y = np.ma.MaskedArray([[1, 127],
| ... [0, 127],
| ... [-1, 127],
| ... [-2, 127]], dtype=np.int8)
| >>> y.ptp(axis=1)
| masked_array(data=[ 126, 127, -128, -127],
| mask=False,
| fill_value=np.int64(999999),
| dtype=int8)
|
| A work-around is to use the `view()` method to view the result as
| unsigned integers with the same bit width:
|
| >>> y.ptp(axis=1).view(np.uint8)
| masked_array(data=[126, 127, 128, 129],
| mask=False,
| fill_value=np.int64(999999),
| dtype=uint8)
|
| put(self, indices, values, mode='raise') from numpy.ma.core.MaskedArray
| Set storage-indexed locations to corresponding values.
|
| Sets self._data.flat[n] = values[n] for each n in indices.
| If `values` is shorter than `indices` then it will repeat.
| If `values` has some masked values, the initial mask is updated
| in consequence, else the corresponding values are unmasked.
|
| Parameters
| ----------
| indices : 1-D array_like
| Target indices, interpreted as integers.
| values : array_like
| Values to place in self._data copy at target indices.
| mode : {'raise', 'wrap', 'clip'}, optional
| Specifies how out-of-bounds indices will behave.
| 'raise' : raise an error.
| 'wrap' : wrap around.
| 'clip' : clip to the range.
|
| Notes
| -----
| `values` can be a scalar or length 1 array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.put([0,4,8],[10,20,30])
| >>> x
| masked_array(
| data=[[10, --, 3],
| [--, 20, --],
| [7, --, 30]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
|
| >>> x.put(4,999)
| >>> x
| masked_array(
| data=[[10, --, 3],
| [--, 999, --],
| [7, --, 30]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
|
| ravel(self, order='C') from numpy.ma.core.MaskedArray
| Returns a 1D version of self, as a view.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| The elements of `a` are read using this index order. 'C' means to
| index the elements in C-like order, with the last axis index
| changing fastest, back to the first axis index changing slowest.
| 'F' means to index the elements in Fortran-like index order, with
| the first index changing fastest, and the last index changing
| slowest. Note that the 'C' and 'F' options take no account of the
| memory layout of the underlying array, and only refer to the order
| of axis indexing. 'A' means to read the elements in Fortran-like
| index order if `m` is Fortran *contiguous* in memory, C-like order
| otherwise. 'K' means to read the elements in the order they occur
| in memory, except for reversing the data when strides are negative.
| By default, 'C' index order is used.
| (Masked arrays currently use 'A' on the data when 'K' is passed.)
|
| Returns
| -------
| MaskedArray
| Output view is of shape ``(self.size,)`` (or
| ``(np.ma.product(self.shape),)``).
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.ravel()
| masked_array(data=[1, --, 3, --, 5, --, 7, --, 9],
| mask=[False, True, False, True, False, True, False, True,
| False],
| fill_value=999999)
|
| repeat(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.repeat(repeats, axis=None)
|
| Repeat elements of an array.
|
| Refer to `numpy.repeat` for full documentation.
|
| See Also
| --------
| numpy.repeat : equivalent function
|
| reshape(self, *s, **kwargs) from numpy.ma.core.MaskedArray
| Give a new shape to the array without changing its data.
|
| Returns a masked array containing the same data, but with a new shape.
| The result is a view on the original array; if this is not possible, a
| ValueError is raised.
|
| Parameters
| ----------
| shape : int or tuple of ints
| The new shape should be compatible with the original shape. If an
| integer is supplied, then the result will be a 1-D array of that
| length.
| order : {'C', 'F'}, optional
| Determines whether the array data should be viewed as in C
| (row-major) or FORTRAN (column-major) order.
|
| Returns
| -------
| reshaped_array : array
| A new view on the array.
|
| See Also
| --------
| reshape : Equivalent function in the masked array module.
| numpy.ndarray.reshape : Equivalent method on ndarray object.
| numpy.reshape : Equivalent function in the NumPy module.
|
| Notes
| -----
| The reshaping operation cannot guarantee that a copy will not be made,
| to modify the shape in place, use ``a.shape = s``
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1])
| >>> x
| masked_array(
| data=[[--, 2],
| [3, --]],
| mask=[[ True, False],
| [False, True]],
| fill_value=999999)
| >>> x = x.reshape((4,1))
| >>> x
| masked_array(
| data=[[--],
| [2],
| [3],
| [--]],
| mask=[[ True],
| [False],
| [False],
| [ True]],
| fill_value=999999)
|
| resize(self, newshape, refcheck=True, order=False) from numpy.ma.core.MaskedArray
| .. warning::
|
| This method does nothing, except raise a ValueError exception. A
| masked array does not own its data and therefore cannot safely be
| resized in place. Use the `numpy.ma.resize` function instead.
|
| This method is difficult to implement safely and may be deprecated in
| future releases of NumPy.
|
| round(self, decimals=0, out=None) from numpy.ma.core.MaskedArray
| Return each element rounded to the given number of decimals.
|
| Refer to `numpy.around` for full documentation.
|
| See Also
| --------
| numpy.ndarray.round : corresponding function for ndarrays
| numpy.around : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> import numpy.ma as ma
| >>> x = ma.array([1.35, 2.5, 1.5, 1.75, 2.25, 2.75],
| ... mask=[0, 0, 0, 1, 0, 0])
| >>> ma.round(x)
| masked_array(data=[1.0, 2.0, 2.0, --, 2.0, 3.0],
| mask=[False, False, False, True, False, False],
| fill_value=1e+20)
|
| set_fill_value = fill_value(self, value=None) from numpy.ma.core.MaskedArray
|
| shrink_mask(self) from numpy.ma.core.MaskedArray
| Reduce a mask to nomask when possible.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| None
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4)
| >>> x.mask
| array([[False, False],
| [False, False]])
| >>> x.shrink_mask()
| masked_array(
| data=[[1, 2],
| [3, 4]],
| mask=False,
| fill_value=999999)
| >>> x.mask
| False
|
| soften_mask(self) from numpy.ma.core.MaskedArray
| Force the mask to soft (default), allowing unmasking by assignment.
|
| Whether the mask of a masked array is hard or soft is determined by
| its `~ma.MaskedArray.hardmask` property. `soften_mask` sets
| `~ma.MaskedArray.hardmask` to ``False`` (and returns the modified
| self).
|
| See Also
| --------
| ma.MaskedArray.hardmask
| ma.MaskedArray.harden_mask
|
| sort(self, axis=-1, kind=None, order=None, endwith=True, fill_value=None, *, stable=False) from numpy.ma.core.MaskedArray
| Sort the array, in-place
|
| Parameters
| ----------
| a : array_like
| Array to be sorted.
| axis : int, 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 : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| The sorting algorithm used.
| order : list, optional
| When `a` is a structured array, this argument specifies which fields
| to compare first, second, and so on. This list does not need to
| include all of the fields.
| endwith : {True, False}, optional
| Whether missing values (if any) should be treated as the largest values
| (True) or the smallest values (False)
| When the array contains unmasked values sorting at the same extremes of the
| datatype, the ordering of these values and the masked values is
| undefined.
| fill_value : scalar or None, optional
| Value used internally for the masked values.
| If ``fill_value`` is not None, it supersedes ``endwith``.
| stable : bool, optional
| Only for compatibility with ``np.sort``. Ignored.
|
| Returns
| -------
| sorted_array : ndarray
| Array of the same type and shape as `a`.
|
| See Also
| --------
| numpy.ndarray.sort : Method to sort an array in-place.
| argsort : Indirect sort.
| lexsort : Indirect stable sort on multiple keys.
| searchsorted : Find elements in a sorted array.
|
| Notes
| -----
| See ``sort`` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
| >>> # Default
| >>> a.sort()
| >>> a
| masked_array(data=[1, 3, 5, --, --],
| mask=[False, False, False, True, True],
| fill_value=999999)
|
| >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
| >>> # Put missing values in the front
| >>> a.sort(endwith=False)
| >>> a
| masked_array(data=[--, --, 1, 3, 5],
| mask=[ True, True, False, False, False],
| fill_value=999999)
|
| >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
| >>> # fill_value takes over endwith
| >>> a.sort(endwith=False, fill_value=3)
| >>> a
| masked_array(data=[1, --, --, 3, 5],
| mask=[False, True, True, False, False],
| fill_value=999999)
|
| squeeze(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.squeeze(axis=None)
|
| Remove axes of length one from `a`.
|
| Refer to `numpy.squeeze` for full documentation.
|
| See Also
| --------
| numpy.squeeze : equivalent function
|
| std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, mean=<no value>) from numpy.ma.core.MaskedArray
| Returns the standard deviation of the array elements along given axis.
|
| Masked entries are ignored.
|
| Refer to `numpy.std` for full documentation.
|
| See Also
| --------
| numpy.ndarray.std : corresponding function for ndarrays
| numpy.std : Equivalent function
|
| sum(self, axis=None, dtype=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the sum of the array elements over the given axis.
|
| Masked elements are set to 0 internally.
|
| Refer to `numpy.sum` for full documentation.
|
| See Also
| --------
| numpy.ndarray.sum : corresponding function for ndarrays
| numpy.sum : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.sum()
| 25
| >>> x.sum(axis=1)
| masked_array(data=[4, 5, 16],
| mask=[False, False, False],
| fill_value=999999)
| >>> x.sum(axis=0)
| masked_array(data=[8, 5, 12],
| mask=[False, False, False],
| fill_value=999999)
| >>> print(type(x.sum(axis=0, dtype=np.int64)[0]))
| <class 'numpy.int64'>
|
| swapaxes(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.swapaxes(axis1, axis2)
|
| Return a view of the array with `axis1` and `axis2` interchanged.
|
| Refer to `numpy.swapaxes` for full documentation.
|
| See Also
| --------
| numpy.swapaxes : equivalent function
|
| take(self, indices, axis=None, out=None, mode='raise') from numpy.ma.core.MaskedArray
|
| tobytes(self, fill_value=None, order='C') from numpy.ma.core.MaskedArray
| Return the array data as a string containing the raw bytes in the array.
|
| The array is filled with a fill value before the string conversion.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| fill_value : scalar, optional
| Value used to fill in the masked values. Default is None, in which
| case `MaskedArray.fill_value` is used.
| order : {'C','F','A'}, optional
| Order of the data item in the copy. Default is 'C'.
|
| - 'C' -- C order (row major).
| - 'F' -- Fortran order (column major).
| - 'A' -- Any, current order of array.
| - None -- Same as 'A'.
|
| See Also
| --------
| numpy.ndarray.tobytes
| tolist, tofile
|
| Notes
| -----
| As for `ndarray.tobytes`, information about the shape, dtype, etc.,
| but also about `fill_value`, will be lost.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
| >>> x.tobytes()
| b'\x01\x00\x00\x00\x00\x00\x00\x00?B\x0f\x00\x00\x00\x00\x00?B\x0f\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00'
|
| tofile(self, fid, sep='', format='%s') from numpy.ma.core.MaskedArray
| Save a masked array to a file in binary format.
|
| .. warning::
| This function is not implemented yet.
|
| Raises
| ------
| NotImplementedError
| When `tofile` is called.
|
| toflex(self) from numpy.ma.core.MaskedArray
| Transforms a masked array into a flexible-type array.
|
| The flexible type array that is returned will have two fields:
|
| * the ``_data`` field stores the ``_data`` part of the array.
| * the ``_mask`` field stores the ``_mask`` part of the array.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| record : ndarray
| A new flexible-type `ndarray` with two fields: the first element
| containing a value, the second element containing the corresponding
| mask boolean. The returned record shape matches self.shape.
|
| Notes
| -----
| A side-effect of transforming a masked array into a flexible `ndarray` is
| that meta information (``fill_value``, ...) will be lost.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.toflex()
| array([[(1, False), (2, True), (3, False)],
| [(4, True), (5, False), (6, True)],
| [(7, False), (8, True), (9, False)]],
| dtype=[('_data', '<i8'), ('_mask', '?')])
|
| tolist(self, fill_value=None) from numpy.ma.core.MaskedArray
| Return the data portion of the masked array as a hierarchical Python list.
|
| Data items are converted to the nearest compatible Python type.
| Masked values are converted to `fill_value`. If `fill_value` is None,
| the corresponding entries in the output list will be ``None``.
|
| Parameters
| ----------
| fill_value : scalar, optional
| The value to use for invalid entries. Default is None.
|
| Returns
| -------
| result : list
| The Python list representation of the masked array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4)
| >>> x.tolist()
| [[1, None, 3], [None, 5, None], [7, None, 9]]
| >>> x.tolist(-999)
| [[1, -999, 3], [-999, 5, -999], [7, -999, 9]]
|
| torecords = toflex(self)
|
| tostring(self, fill_value=None, order='C') from numpy.ma.core.MaskedArray
| A compatibility alias for `tobytes`, with exactly the same behavior.
|
| Despite its name, it returns `bytes` not `str`\ s.
|
| .. deprecated:: 1.19.0
|
| trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None) from numpy.ma.core.MaskedArray
| a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
|
| Return the sum along diagonals of the array.
|
| Refer to `numpy.trace` for full documentation.
|
| See Also
| --------
| numpy.trace : equivalent function
|
| transpose(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.transpose(*axes)
|
| Returns a view of the array with axes transposed.
|
| Refer to `numpy.transpose` for full documentation.
|
| Parameters
| ----------
| axes : None, tuple of ints, or `n` ints
|
| * None or no argument: reverses the order of the axes.
|
| * tuple of ints: `i` in the `j`-th place in the tuple means that the
| array's `i`-th axis becomes the transposed array's `j`-th axis.
|
| * `n` ints: same as an n-tuple of the same ints (this form is
| intended simply as a "convenience" alternative to the tuple form).
|
| Returns
| -------
| p : ndarray
| View of the array with its axes suitably permuted.
|
| See Also
| --------
| transpose : Equivalent function.
| ndarray.T : Array property returning the array transposed.
| ndarray.reshape : Give a new shape to an array without changing its data.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.transpose()
| array([[1, 3],
| [2, 4]])
| >>> a.transpose((1, 0))
| array([[1, 3],
| [2, 4]])
| >>> a.transpose(1, 0)
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.transpose()
| array([1, 2, 3, 4])
|
| unshare_mask(self) from numpy.ma.core.MaskedArray
| Copy the mask and set the `sharedmask` flag to ``False``.
|
| Whether the mask is shared between masked arrays can be seen from
| the `sharedmask` property. `unshare_mask` ensures the mask is not
| shared. A copy of the mask is only made if it was shared.
|
| See Also
| --------
| sharedmask
|
| var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, mean=<no value>) from numpy.ma.core.MaskedArray
| Compute the variance along the specified axis.
|
| 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.
|
| Parameters
| ----------
| a : array_like
| Array containing numbers whose variance is desired. If `a` is not an
| array, a conversion is attempted.
| axis : None or int or tuple of ints, optional
| Axis or axes along which the variance is computed. The default is to
| compute the variance of the flattened array.
|
| .. versionadded:: 1.7.0
|
| If this is a tuple of ints, a variance is performed over multiple axes,
| instead of a single axis or all the axes as before.
| dtype : data-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.
| out : ndarray, 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.
| ddof : {int, float}, optional
| "Delta Degrees of Freedom": the divisor used in the calculation is
| ``N - ddof``, where ``N`` represents the number of elements. By
| default `ddof` is zero. See notes for details about use of `ddof`.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the input array.
|
| If the default value is passed, then `keepdims` will not be
| passed through to the `var` method of sub-classes of
| `ndarray`, however any non-default value will be. If the
| sub-class' method does not implement `keepdims` any
| exceptions will be raised.
| where : array_like of bool, optional
| Elements to include in the variance. See `~numpy.ufunc.reduce` for
| details.
|
| .. versionadded:: 1.20.0
|
| mean : array like, optional
| Provide the mean to prevent its recalculation. The mean should have
| a shape as if it was calculated with ``keepdims=True``.
| The axis for the calculation of the mean should be the same as used in
| the call to this var function.
|
| .. versionadded:: 1.26.0
|
| correction : {int, float}, optional
| Array API compatible name for the ``ddof`` parameter. Only one of them
| can be provided at the same time.
|
| .. versionadded:: 2.0.0
|
| Returns
| -------
| variance : ndarray, see dtype parameter above
| If ``out=None``, returns a new array containing the variance;
| otherwise, a reference to the output array is returned.
|
| See Also
| --------
| std, mean, nanmean, nanstd, nanvar
| :ref:`ufuncs-output-type`
|
| Notes
| -----
| There are several common variants of the array variance calculation.
| Assuming the input `a` is a one-dimensional NumPy array and ``mean`` is
| either provided as an argument or computed as ``a.mean()``, NumPy
| computes the variance of an array as::
|
| N = len(a)
| d2 = abs(a - mean)**2 # abs is for complex `a`
| var = d2.sum() / (N - ddof) # note use of `ddof`
|
| Different values of the argument `ddof` are useful in different
| contexts. NumPy's default ``ddof=0`` corresponds with the expression:
|
| .. math::
|
| \frac{\sum_i{|a_i - \bar{a}|^2 }}{N}
|
| which is sometimes called the "population variance" in the field of
| statistics because it applies the definition of variance to `a` as if `a`
| were a complete population of possible observations.
|
| Many other libraries define the variance of an array differently, e.g.:
|
| .. math::
|
| \frac{\sum_i{|a_i - \bar{a}|^2}}{N - 1}
|
| In statistics, the resulting quantity is sometimed called the "sample
| variance" because if `a` is a random sample from a larger population,
| this calculation provides an unbiased estimate of the variance of the
| population. The use of :math:`N-1` in the denominator is often called
| "Bessel's correction" because it corrects for bias (toward lower values)
| in the variance estimate introduced when the sample mean of `a` is used
| in place of the true mean of the population. For this quantity, use
| ``ddof=1``.
|
| 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.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> np.var(a)
| 1.25
| >>> np.var(a, axis=0)
| array([1., 1.])
| >>> np.var(a, axis=1)
| array([0.25, 0.25])
|
| In single precision, var() can be inaccurate:
|
| >>> a = np.zeros((2, 512*512), dtype=np.float32)
| >>> a[0, :] = 1.0
| >>> a[1, :] = 0.1
| >>> np.var(a)
| 0.20250003
|
| Computing the variance in float64 is more accurate:
|
| >>> np.var(a, dtype=np.float64)
| 0.20249999932944759 # may vary
| >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
| 0.2025
|
| Specifying a where argument:
|
| >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
| >>> np.var(a)
| 6.833333333333333 # may vary
| >>> np.var(a, where=[[True], [True], [False]])
| 4.0
|
| Using the mean keyword to save computation time:
|
| >>> import numpy as np
| >>> from timeit import timeit
| >>>
| >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
| >>> mean = np.mean(a, axis=1, keepdims=True)
| >>>
| >>> g = globals()
| >>> n = 10000
| >>> t1 = timeit("var = np.var(a, axis=1, mean=mean)", globals=g, number=n)
| >>> t2 = timeit("var = np.var(a, axis=1)", globals=g, number=n)
| >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
| #doctest: +SKIP
| Percentage execution time saved 32%
|
| view(self, dtype=None, type=None, fill_value=None) from numpy.ma.core.MaskedArray
| Return a view of the MaskedArray data.
|
| Parameters
| ----------
| dtype : data-type or ndarray sub-class, optional
| Data-type descriptor of the returned view, e.g., float32 or int16.
| The default, None, results in the view having the same data-type
| as `a`. As with ``ndarray.view``, dtype can also be specified as
| an ndarray sub-class, which then specifies the type of the
| returned object (this is equivalent to setting the ``type``
| parameter).
| type : Python type, optional
| Type of the returned view, either ndarray or a subclass. The
| default None results in type preservation.
| fill_value : scalar, optional
| The value to use for invalid entries (None by default).
| If None, then this argument is inferred from the passed `dtype`, or
| in its absence the original array, as discussed in the notes below.
|
| See Also
| --------
| numpy.ndarray.view : Equivalent method on ndarray object.
|
| Notes
| -----
|
| ``a.view()`` is used two different ways:
|
| ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| of the array's memory with a different data-type. This can cause a
| reinterpretation of the bytes of memory.
|
| ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| returns an instance of `ndarray_subclass` that looks at the same array
| (same shape, dtype, etc.) This does not cause a reinterpretation of the
| memory.
|
| If `fill_value` is not specified, but `dtype` is specified (and is not
| an ndarray sub-class), the `fill_value` of the MaskedArray will be
| reset. If neither `fill_value` nor `dtype` are specified (or if
| `dtype` is an ndarray sub-class), then the fill value is preserved.
| Finally, if `fill_value` is specified, but `dtype` is not, the fill
| value is set to the specified value.
|
| For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| bytes per entry than the previous dtype (for example, converting a
| regular array to a structured array), then the behavior of the view
| cannot be predicted just from the superficial appearance of ``a`` (shown
| by ``print(a)``). It also depends on exactly how ``a`` is stored in
| memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus
| defined as a slice or transpose, etc., the view may give different
| results.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, data=None, mask=np.False_, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None) from numpy.ma.core.MaskedArray
| Create a new masked array from scratch.
|
| Notes
| -----
| A masked array can also be created by taking a .view(MaskedArray).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| T
|
| baseclass
| Class of the underlying data (read-only).
|
| data
| Returns the underlying data, as a view of the masked array.
|
| If the underlying data is a subclass of :class:`numpy.ndarray`, it is
| returned as such.
|
| >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
| >>> x.data
| matrix([[1, 2],
| [3, 4]])
|
| The type of the data can be accessed through the :attr:`baseclass`
| attribute.
|
| hardmask
| Specifies whether values can be unmasked through assignments.
|
| By default, assigning definite values to masked array entries will
| unmask them. When `hardmask` is ``True``, the mask will not change
| through assignments.
|
| See Also
| --------
| ma.MaskedArray.harden_mask
| ma.MaskedArray.soften_mask
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(10)
| >>> m = np.ma.masked_array(x, x>5)
| >>> assert not m.hardmask
|
| Since `m` has a soft mask, assigning an element value unmasks that
| element:
|
| >>> m[8] = 42
| >>> m
| masked_array(data=[0, 1, 2, 3, 4, 5, --, --, 42, --],
| mask=[False, False, False, False, False, False,
| True, True, False, True],
| fill_value=999999)
|
| After hardening, the mask is not affected by assignments:
|
| >>> hardened = np.ma.harden_mask(m)
| >>> assert m.hardmask and hardened is m
| >>> m[:] = 23
| >>> m
| masked_array(data=[23, 23, 23, 23, 23, 23, --, --, 23, --],
| mask=[False, False, False, False, False, False,
| True, True, False, True],
| fill_value=999999)
|
| imag
| The imaginary part of the masked array.
|
| This property is a view on the imaginary part of this `MaskedArray`.
|
| See Also
| --------
| real
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.imag
| masked_array(data=[1.0, --, 1.6],
| mask=[False, True, False],
| fill_value=1e+20)
|
| mT
| Return the matrix-transpose of the masked array.
|
| The matrix transpose is the transpose of the last two dimensions, even
| if the array is of higher dimension.
|
| .. versionadded:: 2.0
|
| Returns
| -------
| result: MaskedArray
| The masked array with the last two dimensions transposed
|
| Raises
| ------
| ValueError
| If the array is of dimension less than 2.
|
| See Also
| --------
| ndarray.mT:
| Equivalent method for arrays
|
| real
| The real part of the masked array.
|
| This property is a view on the real part of this `MaskedArray`.
|
| See Also
| --------
| imag
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.real
| masked_array(data=[1.0, --, 3.45],
| mask=[False, True, False],
| fill_value=1e+20)
|
| sharedmask
| Share status of the mask (read-only).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| dtype
| Data-type of the array's elements.
|
| .. warning::
|
| Setting ``arr.dtype`` is discouraged and may be deprecated in the
| future. Setting will replace the ``dtype`` without modifying the
| memory (see also `ndarray.view` and `ndarray.astype`).
|
| Parameters
| ----------
| None
|
| Returns
| -------
| d : numpy dtype object
|
| See Also
| --------
| ndarray.astype : Cast the values contained in the array to a new data-type.
| ndarray.view : Create a view of the same data but a different data-type.
| numpy.dtype
|
| Examples
| --------
| >>> x
| array([[0, 1],
| [2, 3]])
| >>> x.dtype
| dtype('int32')
| >>> type(x.dtype)
| <type 'numpy.dtype'>
|
| fill_value
| The filling value of the masked array is a scalar. When setting, None
| will set to a default based on the data type.
|
| Examples
| --------
| >>> import numpy as np
| >>> for dt in [np.int32, np.int64, np.float64, np.complex128]:
| ... np.ma.array([0, 1], dtype=dt).get_fill_value()
| ...
| np.int64(999999)
| np.int64(999999)
| np.float64(1e+20)
| np.complex128(1e+20+0j)
|
| >>> x = np.ma.array([0, 1.], fill_value=-np.inf)
| >>> x.fill_value
| np.float64(-inf)
| >>> x.fill_value = np.pi
| >>> x.fill_value
| np.float64(3.1415926535897931)
|
| Reset to default:
|
| >>> x.fill_value = None
| >>> x.fill_value
| np.float64(1e+20)
|
| flat
| Return a flat iterator, or set a flattened version of self to value.
|
| mask
| Current mask.
|
| recordmask
| Get or set the mask of the array if it has no named fields. For
| structured arrays, returns a ndarray of booleans where entries are
| ``True`` if **all** the fields are masked, ``False`` otherwise:
|
| >>> x = np.ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
| ... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)],
| ... dtype=[('a', int), ('b', int)])
| >>> x.recordmask
| array([False, False, True, False, False])
|
| shape
| Tuple of array dimensions.
|
| The shape property is usually used to get the current shape of an array,
| but may also be used to reshape the array in-place by assigning a tuple of
| array dimensions to it. As with `numpy.reshape`, one of the new shape
| dimensions can be -1, in which case its value is inferred from the size of
| the array and the remaining dimensions. Reshaping an array in-place will
| fail if a copy is required.
|
| .. warning::
|
| Setting ``arr.shape`` is discouraged and may be deprecated in the
| future. Using `ndarray.reshape` is the preferred approach.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3, 4])
| >>> x.shape
| (4,)
| >>> y = np.zeros((2, 3, 4))
| >>> y.shape
| (2, 3, 4)
| >>> y.shape = (3, 8)
| >>> y
| array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| >>> y.shape = (3, 6)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: total size of new array must be unchanged
| >>> np.zeros((4,2))[::2].shape = (-1,)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| AttributeError: Incompatible shape for in-place modification. Use
| `.reshape()` to make a copy with the desired shape.
|
| See Also
| --------
| numpy.shape : Equivalent getter function.
| numpy.reshape : Function similar to setting ``shape``.
| ndarray.reshape : Method similar to setting ``shape``.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __array_priority__ = 15
|
| __hash__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.ndarray:
|
| __abs__(self, /)
| abs(self)
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| a.__array__([dtype], *, copy=None)
|
| For ``dtype`` parameter it returns a new reference to self if
| ``dtype`` is not given or it matches array's data type.
| A new array of provided data type is returned if ``dtype``
| is different from the current data type of the array.
| For ``copy`` parameter it returns a new reference to self if
| ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| parameter. The method returns a new array for ``copy=True``, regardless of
| ``dtype`` parameter.
|
| A more detailed explanation of the ``__array__`` interface
| can be found in :ref:`dunder_array.interface`.
|
| __array_function__(...)
|
| __array_namespace__(...)
|
| __array_ufunc__(...)
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __complex__(...)
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __copy__(...)
| a.__copy__()
|
| Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
|
| Equivalent to ``a.copy(order='K')``.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __dlpack__(...)
| a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
|
| DLPack Protocol: Part of the Array API.
|
| __dlpack_device__(...)
| a.__dlpack_device__()
|
| DLPack Protocol: Part of the Array API.
|
| __format__(...)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __ilshift__(self, value, /)
| Return self<<=value.
|
| __imatmul__(self, value, /)
| Return self@=value.
|
| __imod__(self, value, /)
| Return self%=value.
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __invert__(self, /)
| ~self
|
| __ior__(self, value, /)
| Return self|=value.
|
| __irshift__(self, value, /)
| Return self>>=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __len__(self, /)
| Return len(self).
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __matmul__(self, value, /)
| Return self@value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce_ex__(...)
| Helper for pickle.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmatmul__(self, value, /)
| Return value@self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __xor__(self, value, /)
| Return self^value.
|
| astype(...)
| a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
|
| Copy of the array, cast to a specified type.
|
| Parameters
| ----------
| dtype : str or dtype
| Typecode or data-type to which the array is cast.
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout order of the result.
| '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.
| Default is 'K'.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'unsafe'
| for backwards compatibility.
|
| * '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.
| subok : bool, optional
| If True, then sub-classes will be passed-through (default), otherwise
| the returned array will be forced to be a base-class array.
| copy : bool, optional
| By default, astype always returns a newly allocated array. If this
| is set to false, and the `dtype`, `order`, and `subok`
| requirements are satisfied, the input array is returned instead
| of a copy.
|
| Returns
| -------
| arr_t : ndarray
| Unless `copy` is False and the other conditions for returning the input
| array are satisfied (see description for `copy` input parameter), `arr_t`
| is a new array of the same shape as the input array, with dtype, order
| given by `dtype`, `order`.
|
| Notes
| -----
| .. versionchanged:: 1.17.0
| Casting between a simple data type and a structured one is possible only
| for "unsafe" casting. Casting to multiple fields is allowed, but
| casting from multiple fields is not.
|
| .. versionchanged:: 1.9.0
| Casting from numeric to string types in 'safe' casting mode requires
| that the string dtype length is long enough to store the max
| integer/float value converted.
|
| Raises
| ------
| ComplexWarning
| When casting from complex to float or int. To avoid this,
| one should use ``a.real.astype(t)``.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 2.5])
| >>> x
| array([1. , 2. , 2.5])
|
| >>> x.astype(int)
| array([1, 2, 2])
|
| byteswap(...)
| a.byteswap(inplace=False)
|
| Swap the bytes of the array elements
|
| Toggle between low-endian and big-endian data representation by
| returning a byteswapped array, optionally swapped in-place.
| Arrays of byte-strings are not swapped. The real and imaginary
| parts of a complex number are swapped individually.
|
| Parameters
| ----------
| inplace : bool, optional
| If ``True``, swap bytes in-place, default is ``False``.
|
| Returns
| -------
| out : ndarray
| The byteswapped array. If `inplace` is ``True``, this is
| a view to self.
|
| Examples
| --------
| >>> import numpy as np
| >>> A = np.array([1, 256, 8755], dtype=np.int16)
| >>> list(map(hex, A))
| ['0x1', '0x100', '0x2233']
| >>> A.byteswap(inplace=True)
| array([ 256, 1, 13090], dtype=int16)
| >>> list(map(hex, A))
| ['0x100', '0x1', '0x3322']
|
| Arrays of byte-strings are not swapped
|
| >>> A = np.array([b'ceg', b'fac'])
| >>> A.byteswap()
| array([b'ceg', b'fac'], dtype='|S3')
|
| ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| the same values but different representation in memory
|
| >>> A = np.array([1, 2, 3])
| >>> A.view(np.uint8)
| array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| 0, 0], dtype=uint8)
| >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| array([1, 2, 3])
| >>> A.view(np.uint8)
| array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| 0, 3], dtype=uint8)
|
| choose(...)
| a.choose(choices, out=None, mode='raise')
|
| Use an index array to construct a new array from a set of choices.
|
| Refer to `numpy.choose` for full documentation.
|
| See Also
| --------
| numpy.choose : equivalent function
|
| clip(...)
| a.clip(min=None, max=None, out=None, **kwargs)
|
| Return an array whose values are limited to ``[min, max]``.
| One of max or min must be given.
|
| Refer to `numpy.clip` for full documentation.
|
| See Also
| --------
| numpy.clip : equivalent function
|
| conj(...)
| a.conj()
|
| Complex-conjugate all elements.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| conjugate(...)
| a.conjugate()
|
| Return the complex conjugate, element-wise.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| dump(...)
| a.dump(file)
|
| Dump a pickle of the array to the specified file.
| The array can be read back with pickle.load or numpy.load.
|
| Parameters
| ----------
| file : str or Path
| A string naming the dump file.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| dumps(...)
| a.dumps()
|
| Returns the pickle of the array as a string.
| pickle.loads will convert the string back to an array.
|
| Parameters
| ----------
| None
|
| fill(...)
| a.fill(value)
|
| Fill the array with a scalar value.
|
| Parameters
| ----------
| value : scalar
| All elements of `a` will be assigned this value.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([1, 2])
| >>> a.fill(0)
| >>> a
| array([0, 0])
| >>> a = np.empty(2)
| >>> a.fill(1)
| >>> a
| array([1., 1.])
|
| Fill expects a scalar value and always behaves the same as assigning
| to a single array element. The following is a rare example where this
| distinction is important:
|
| >>> a = np.array([None, None], dtype=object)
| >>> a[0] = np.array(3)
| >>> a
| array([array(3), None], dtype=object)
| >>> a.fill(np.array(3))
| >>> a
| array([array(3), array(3)], dtype=object)
|
| Where other forms of assignments will unpack the array being assigned:
|
| >>> a[...] = np.array(3)
| >>> a
| array([3, 3], dtype=object)
|
| getfield(...)
| a.getfield(dtype, offset=0)
|
| Returns a field of the given array as a certain type.
|
| A field is a view of the array data with a given data-type. The values in
| the view are determined by the given type and the offset into the current
| array in bytes. The offset needs to be such that the view dtype fits in the
| array dtype; for example an array of dtype complex128 has 16-byte elements.
| If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| between 0 and 12 bytes.
|
| Parameters
| ----------
| dtype : str or dtype
| The data type of the view. The dtype size of the view can not be larger
| than that of the array itself.
| offset : int
| Number of bytes to skip before beginning the element view.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.diag([1.+1.j]*2)
| >>> x[1, 1] = 2 + 4.j
| >>> x
| array([[1.+1.j, 0.+0.j],
| [0.+0.j, 2.+4.j]])
| >>> x.getfield(np.float64)
| array([[1., 0.],
| [0., 2.]])
|
| By choosing an offset of 8 bytes we can select the complex part of the
| array for our view:
|
| >>> x.getfield(np.float64, offset=8)
| array([[1., 0.],
| [0., 4.]])
|
| item(...)
| a.item(*args)
|
| Copy an element of an array to a standard Python scalar and return it.
|
| Parameters
| ----------
| \*args : Arguments (variable number and type)
|
| * none: in this case, the method only works for arrays
| with one element (`a.size == 1`), which element is
| copied into a standard Python scalar object and returned.
|
| * int_type: this argument is interpreted as a flat index into
| the array, specifying which element to copy and return.
|
| * tuple of int_types: functions as does a single int_type argument,
| except that the argument is interpreted as an nd-index into the
| array.
|
| Returns
| -------
| z : Standard Python scalar object
| A copy of the specified element of the array as a suitable
| Python scalar
|
| Notes
| -----
| When the data type of `a` is longdouble or clongdouble, item() returns
| a scalar array object because there is no available Python scalar that
| would not lose information. Void arrays return a buffer object for item(),
| unless fields are defined, in which case a tuple is returned.
|
| `item` is very similar to a[args], except, instead of an array scalar,
| a standard Python scalar is returned. This can be useful for speeding up
| access to elements of the array and doing arithmetic on elements of the
| array using Python's optimized math.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.random.seed(123)
| >>> x = np.random.randint(9, size=(3, 3))
| >>> x
| array([[2, 2, 6],
| [1, 3, 6],
| [1, 0, 1]])
| >>> x.item(3)
| 1
| >>> x.item(7)
| 0
| >>> x.item((0, 1))
| 2
| >>> x.item((2, 2))
| 1
|
| For an array with object dtype, elements are returned as-is.
|
| >>> a = np.array([np.int64(1)], dtype=object)
| >>> a.item() #return np.int64
| np.int64(1)
|
| searchsorted(...)
| a.searchsorted(v, side='left', sorter=None)
|
| Find indices where elements of v should be inserted in a to maintain order.
|
| For full documentation, see `numpy.searchsorted`
|
| See Also
| --------
| numpy.searchsorted : equivalent function
|
| setfield(...)
| a.setfield(val, dtype, offset=0)
|
| Put a value into a specified place in a field defined by a data-type.
|
| Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| bytes into the field.
|
| Parameters
| ----------
| val : object
| Value to be placed in field.
| dtype : dtype object
| Data-type of the field in which to place `val`.
| offset : int, optional
| The number of bytes into the field at which to place `val`.
|
| Returns
| -------
| None
|
| See Also
| --------
| getfield
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.eye(3)
| >>> x.getfield(np.float64)
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
| >>> x.setfield(3, np.int32)
| >>> x.getfield(np.int32)
| array([[3, 3, 3],
| [3, 3, 3],
| [3, 3, 3]], dtype=int32)
| >>> x
| array([[1.0e+000, 1.5e-323, 1.5e-323],
| [1.5e-323, 1.0e+000, 1.5e-323],
| [1.5e-323, 1.5e-323, 1.0e+000]])
| >>> x.setfield(np.eye(3), np.int32)
| >>> x
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
|
| setflags(...)
| a.setflags(write=None, align=None, uic=None)
|
| Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| respectively.
|
| These Boolean-valued flags affect how numpy interprets the memory
| area used by `a` (see Notes below). The ALIGNED flag can only
| be set to True if the data is actually aligned according to the type.
| The WRITEBACKIFCOPY flag can never be set
| to True. The flag WRITEABLE can only be set to True if the array owns its
| own memory, or the ultimate owner of the memory exposes a writeable buffer
| interface, or is a string. (The exception for string is made so that
| unpickling can be done without copying memory.)
|
| Parameters
| ----------
| write : bool, optional
| Describes whether or not `a` can be written to.
| align : bool, optional
| Describes whether or not `a` is aligned properly for its type.
| uic : bool, optional
| Describes whether or not `a` is a copy of another "base" array.
|
| Notes
| -----
| Array flags provide information about how the memory area used
| for the array is to be interpreted. There are 7 Boolean flags
| in use, only three of which can be changed by the user:
| WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
|
| WRITEABLE (W) the data area can be written to;
|
| ALIGNED (A) the data and strides are aligned appropriately for the hardware
| (as determined by the compiler);
|
| WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| called, the base array will be updated with the contents of this array.
|
| All flags can be accessed using the single (upper case) letter as well
| as the full name.
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.array([[3, 1, 7],
| ... [2, 0, 0],
| ... [8, 5, 9]])
| >>> y
| array([[3, 1, 7],
| [2, 0, 0],
| [8, 5, 9]])
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
| >>> y.setflags(write=0, align=0)
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : False
| ALIGNED : False
| WRITEBACKIFCOPY : False
| >>> y.setflags(uic=1)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: cannot set WRITEBACKIFCOPY flag to True
|
| to_device(...)
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.ndarray:
|
| __class_getitem__(...)
| a.__class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.ndarray` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.ndarray` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.ndarray[Any, np.dtype[Any]]
| numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
| numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.ndarray:
|
| __array_interface__
| Array protocol: Python side.
|
| __array_struct__
| Array protocol: C-struct side.
|
| base
| Base object if memory is from some other object.
|
| Examples
| --------
| The base of an array that owns its memory is None:
|
| >>> import numpy as np
| >>> x = np.array([1,2,3,4])
| >>> x.base is None
| True
|
| Slicing creates a view, whose memory is shared with x:
|
| >>> y = x[2:]
| >>> y.base is x
| True
|
| ctypes
| An object to simplify the interaction of the array with the ctypes
| module.
|
| This attribute creates an object that makes it easier to use arrays
| when calling shared libraries with the ctypes module. The returned
| object has, among others, data, shape, and strides attributes (see
| Notes below) which themselves return ctypes objects that can be used
| as arguments to a shared library.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| c : Python object
| Possessing attributes data, shape, strides, etc.
|
| See Also
| --------
| numpy.ctypeslib
|
| Notes
| -----
| Below are the public attributes of this object which were documented
| in "Guide to NumPy" (we have omitted undocumented public attributes,
| as well as documented private attributes):
|
| .. autoattribute:: numpy._core._internal._ctypes.data
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.shape
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.strides
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.data_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.shape_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.strides_as
| :noindex:
|
| If the ctypes module is not available, then the ctypes attribute
| of array objects still returns something useful, but ctypes objects
| are not returned and errors may be raised instead. In particular,
| the object will still have the ``as_parameter`` attribute which will
| return an integer equal to the data attribute.
|
| Examples
| --------
| >>> import numpy as np
| >>> import ctypes
| >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| >>> x
| array([[0, 1],
| [2, 3]], dtype=int32)
| >>> x.ctypes.data
| 31962608 # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| c_uint(0)
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| c_ulong(4294967296)
| >>> x.ctypes.shape
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| >>> x.ctypes.strides
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
|
| device
|
| flags
| Information about the memory layout of the array.
|
| Attributes
| ----------
| C_CONTIGUOUS (C)
| The data is in a single, C-style contiguous segment.
| F_CONTIGUOUS (F)
| The data is in a single, Fortran-style contiguous segment.
| OWNDATA (O)
| The array owns the memory it uses or borrows it from another object.
| WRITEABLE (W)
| The data area can be written to. Setting this to False locks
| the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| from its base array at creation time, but a view of a writeable
| array may be subsequently locked while the base array remains writeable.
| (The opposite is not true, in that a view of a locked array may not
| be made writeable. However, currently, locking a base object does not
| lock any views that already reference it, so under that circumstance it
| is possible to alter the contents of a locked array via a previously
| created writeable view onto it.) Attempting to change a non-writeable
| array raises a RuntimeError exception.
| ALIGNED (A)
| The data and all elements are aligned appropriately for the hardware.
| WRITEBACKIFCOPY (X)
| This array is a copy of some other array. The C-API function
| PyArray_ResolveWritebackIfCopy must be called before deallocating
| to the base array will be updated with the contents of this array.
| FNC
| F_CONTIGUOUS and not C_CONTIGUOUS.
| FORC
| F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| BEHAVED (B)
| ALIGNED and WRITEABLE.
| CARRAY (CA)
| BEHAVED and C_CONTIGUOUS.
| FARRAY (FA)
| BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
|
| Notes
| -----
| The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| names are only supported in dictionary access.
|
| Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| changed by the user, via direct assignment to the attribute or dictionary
| entry, or by calling `ndarray.setflags`.
|
| The array flags cannot be set arbitrarily:
|
| - WRITEBACKIFCOPY can only be set ``False``.
| - ALIGNED can only be set ``True`` if the data is truly aligned.
| - WRITEABLE can only be set ``True`` if the array owns its own memory
| or the ultimate owner of the memory exposes a writeable buffer
| interface or is a string.
|
| Arrays can be both C-style and Fortran-style contiguous simultaneously.
| This is clear for 1-dimensional arrays, but can also be true for higher
| dimensional arrays.
|
| Even for contiguous arrays a stride for a given dimension
| ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| or the array has no elements.
| It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| Fortran-style contiguous arrays is true.
|
| itemset
|
| itemsize
| Length of one array element in bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1,2,3], dtype=np.float64)
| >>> x.itemsize
| 8
| >>> x = np.array([1,2,3], dtype=np.complex128)
| >>> x.itemsize
| 16
|
| nbytes
| Total bytes consumed by the elements of the array.
|
| Notes
| -----
| Does not include memory consumed by non-element attributes of the
| array object.
|
| See Also
| --------
| sys.getsizeof
| Memory consumed by the object itself without parents in case view.
| This does include memory consumed by non-element attributes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3,5,2), dtype=np.complex128)
| >>> x.nbytes
| 480
| >>> np.prod(x.shape) * x.itemsize
| 480
|
| ndim
| Number of array dimensions.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3])
| >>> x.ndim
| 1
| >>> y = np.zeros((2, 3, 4))
| >>> y.ndim
| 3
|
| newbyteorder
|
| size
| Number of elements in the array.
|
| Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| dimensions.
|
| Notes
| -----
| `a.size` returns a standard arbitrary precision Python integer. This
| may not be the case with other methods of obtaining the same value
| (like the suggested ``np.prod(a.shape)``, which returns an instance
| of ``np.int_``), and may be relevant if the value is used further in
| calculations that may overflow a fixed size integer type.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| >>> x.size
| 30
| >>> np.prod(x.shape)
| 30
|
| strides
| Tuple of bytes to step in each dimension when traversing an array.
|
| The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| is::
|
| offset = sum(np.array(i) * a.strides)
|
| A more detailed explanation of strides can be found in
| :ref:`arrays.ndarray`.
|
| .. warning::
|
| Setting ``arr.strides`` is discouraged and may be deprecated in the
| future. `numpy.lib.stride_tricks.as_strided` should be preferred
| to create a new view of the same data in a safer way.
|
| Notes
| -----
| Imagine an array of 32-bit integers (each 4 bytes)::
|
| x = np.array([[0, 1, 2, 3, 4],
| [5, 6, 7, 8, 9]], dtype=np.int32)
|
| This array is stored in memory as 40 bytes, one after the other
| (known as a contiguous block of memory). The strides of an array tell
| us how many bytes we have to skip in memory to move to the next position
| along a certain axis. For example, we have to skip 4 bytes (1 value) to
| move to the next column, but 20 bytes (5 values) to get to the same
| position in the next row. As such, the strides for the array `x` will be
| ``(20, 4)``.
|
| See Also
| --------
| numpy.lib.stride_tricks.as_strided
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| >>> y
| array([[[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]],
| [[12, 13, 14, 15],
| [16, 17, 18, 19],
| [20, 21, 22, 23]]])
| >>> y.strides
| (48, 16, 4)
| >>> y[1,1,1]
| 17
| >>> offset=sum(y.strides * np.array((1,1,1)))
| >>> offset/y.itemsize
| 17
|
| >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| >>> x.strides
| (32, 4, 224, 1344)
| >>> i = np.array([3,5,2,2])
| >>> offset = sum(i * x.strides)
| >>> x[3,5,2,2]
| 813
| >>> offset / x.itemsize
| 813
bool_ = class bool(generic)
| Boolean type (True or False), stored as a byte.
|
| .. warning::
|
| The :class:`bool` type is not a subclass of the :class:`int_` type
| (the :class:`bool` is not even a number type). This is different
| than Python's default implementation of :class:`bool` as a
| sub-class of :class:`int`.
|
| :Character code: ``'?'``
|
| Method resolution order:
| bool
| generic
| builtins.object
|
| Methods defined here:
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __rand__(self, value, /)
| Return value&self.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __str__(self, /)
| Return str(self).
|
| __xor__(self, value, /)
| Return self^value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| NumPy array scalar formatter
|
| __getitem__(self, key, /)
| Return self[key].
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| Helper for pickle.
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __setstate__(...)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| base
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.base`.
|
| data
| Pointer to start of data.
|
| device
|
| dtype
| Get array data-descriptor.
|
| flags
| The integer value of flags.
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
masked_array = class MaskedArray(numpy.ndarray)
| masked_array(data=None, mask=np.False_, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None)
|
| An array class with possibly masked values.
|
| Masked values of True exclude the corresponding element from any
| computation.
|
| Construction::
|
| x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True,
| ndmin=0, fill_value=None, keep_mask=True, hard_mask=None,
| shrink=True, order=None)
|
| Parameters
| ----------
| data : array_like
| Input data.
| mask : sequence, optional
| Mask. Must be convertible to an array of booleans with the same
| shape as `data`. True indicates a masked (i.e. invalid) data.
| dtype : dtype, optional
| Data type of the output.
| If `dtype` is None, the type of the data argument (``data.dtype``)
| is used. If `dtype` is not None and different from ``data.dtype``,
| a copy is performed.
| copy : bool, optional
| Whether to copy the input data (True), or to use a reference instead.
| Default is False.
| subok : bool, optional
| Whether to return a subclass of `MaskedArray` if possible (True) or a
| plain `MaskedArray`. Default is True.
| ndmin : int, optional
| Minimum number of dimensions. Default is 0.
| fill_value : scalar, optional
| Value used to fill in the masked values when necessary.
| If None, a default based on the data-type is used.
| keep_mask : bool, optional
| Whether to combine `mask` with the mask of the input data, if any
| (True), or to use only `mask` for the output (False). Default is True.
| hard_mask : bool, optional
| Whether to use a hard mask or not. With a hard mask, masked values
| cannot be unmasked. Default is False.
| shrink : bool, optional
| Whether to force compression of an empty mask. Default is True.
| order : {'C', 'F', 'A'}, optional
| Specify the order of the array. If order is 'C', then the array
| will be in C-contiguous order (last-index varies the fastest).
| If order is 'F', then the returned array will be in
| Fortran-contiguous order (first-index varies the fastest).
| If order is 'A' (default), then the returned array may be
| in any order (either C-, Fortran-contiguous, or even discontiguous),
| unless a copy is required, in which case it will be C-contiguous.
|
| Examples
| --------
| >>> import numpy as np
|
| The ``mask`` can be initialized with an array of boolean values
| with the same shape as ``data``.
|
| >>> data = np.arange(6).reshape((2, 3))
| >>> np.ma.MaskedArray(data, mask=[[False, True, False],
| ... [False, False, True]])
| masked_array(
| data=[[0, --, 2],
| [3, 4, --]],
| mask=[[False, True, False],
| [False, False, True]],
| fill_value=999999)
|
| Alternatively, the ``mask`` can be initialized to homogeneous boolean
| array with the same shape as ``data`` by passing in a scalar
| boolean value:
|
| >>> np.ma.MaskedArray(data, mask=False)
| masked_array(
| data=[[0, 1, 2],
| [3, 4, 5]],
| mask=[[False, False, False],
| [False, False, False]],
| fill_value=999999)
|
| >>> np.ma.MaskedArray(data, mask=True)
| masked_array(
| data=[[--, --, --],
| [--, --, --]],
| mask=[[ True, True, True],
| [ True, True, True]],
| fill_value=999999,
| dtype=int64)
|
| .. note::
| The recommended practice for initializing ``mask`` with a scalar
| boolean value is to use ``True``/``False`` rather than
| ``np.True_``/``np.False_``. The reason is :attr:`nomask`
| is represented internally as ``np.False_``.
|
| >>> np.False_ is np.ma.nomask
| True
|
| Method resolution order:
| MaskedArray
| numpy.ndarray
| builtins.object
|
| Methods defined here:
|
| __add__(self, other) from numpy.ma.core.MaskedArray
| Add self to other, and return a new masked array.
|
| __array_finalize__(self, obj) from numpy.ma.core.MaskedArray
| Finalizes the masked array.
|
| __array_wrap__(self, obj, context=None, return_scalar=False) from numpy.ma.core.MaskedArray
| Special hook for ufuncs.
|
| Wraps the numpy array and sets the mask according to context.
|
| __deepcopy__(self, memo=None) from numpy.ma.core.MaskedArray
| a.__deepcopy__(memo, /)
|
| Used if :func:`copy.deepcopy` is called on an array.
|
| __div__(self, other) from numpy.ma.core.MaskedArray
| Divide other into self, and return a new masked array.
|
| __eq__(self, other) from numpy.ma.core.MaskedArray
| Check whether other equals self elementwise.
|
| When either of the elements is masked, the result is masked as well,
| but the underlying boolean data are still set, with self and other
| considered equal if both are masked, and unequal otherwise.
|
| For structured arrays, all fields are combined, with masked values
| ignored. The result is masked if all fields were masked, with self
| and other considered equal only if both were fully masked.
|
| __float__(self) from numpy.ma.core.MaskedArray
| Convert to float.
|
| __floordiv__(self, other) from numpy.ma.core.MaskedArray
| Divide other into self, and return a new masked array.
|
| __ge__(self, other) from numpy.ma.core.MaskedArray
| Return self>=value.
|
| __getitem__(self, indx) from numpy.ma.core.MaskedArray
| x.__getitem__(y) <==> x[y]
|
| Return the item described by i, as a masked array.
|
| __getstate__(self) from numpy.ma.core.MaskedArray
| Return the internal state of the masked array, for pickling
| purposes.
|
| __gt__(self, other) from numpy.ma.core.MaskedArray
| Return self>value.
|
| __iadd__(self, other) from numpy.ma.core.MaskedArray
| Add other to self in-place.
|
| __idiv__(self, other) from numpy.ma.core.MaskedArray
| Divide self by other in-place.
|
| __ifloordiv__(self, other) from numpy.ma.core.MaskedArray
| Floor divide self by other in-place.
|
| __imul__(self, other) from numpy.ma.core.MaskedArray
| Multiply self by other in-place.
|
| __int__(self) from numpy.ma.core.MaskedArray
| Convert to int.
|
| __ipow__(self, other) from numpy.ma.core.MaskedArray
| Raise self to the power other, in place.
|
| __isub__(self, other) from numpy.ma.core.MaskedArray
| Subtract other from self in-place.
|
| __itruediv__(self, other) from numpy.ma.core.MaskedArray
| True divide self by other in-place.
|
| __le__(self, other) from numpy.ma.core.MaskedArray
| Return self<=value.
|
| __lt__(self, other) from numpy.ma.core.MaskedArray
| Return self<value.
|
| __mul__(self, other) from numpy.ma.core.MaskedArray
| Multiply self by other, and return a new masked array.
|
| __ne__(self, other) from numpy.ma.core.MaskedArray
| Check whether other does not equal self elementwise.
|
| When either of the elements is masked, the result is masked as well,
| but the underlying boolean data are still set, with self and other
| considered equal if both are masked, and unequal otherwise.
|
| For structured arrays, all fields are combined, with masked values
| ignored. The result is masked if all fields were masked, with self
| and other considered equal only if both were fully masked.
|
| __pow__(self, other) from numpy.ma.core.MaskedArray
| Raise self to the power other, masking the potential NaNs/Infs
|
| __radd__(self, other) from numpy.ma.core.MaskedArray
| Add other to self, and return a new masked array.
|
| __reduce__(self) from numpy.ma.core.MaskedArray
| Return a 3-tuple for pickling a MaskedArray.
|
| __repr__(self) from numpy.ma.core.MaskedArray
| Literal string representation.
|
| __rfloordiv__(self, other) from numpy.ma.core.MaskedArray
| Divide self into other, and return a new masked array.
|
| __rmul__(self, other) from numpy.ma.core.MaskedArray
| Multiply other by self, and return a new masked array.
|
| __rpow__(self, other) from numpy.ma.core.MaskedArray
| Raise other to the power self, masking the potential NaNs/Infs
|
| __rsub__(self, other) from numpy.ma.core.MaskedArray
| Subtract self from other, and return a new masked array.
|
| __rtruediv__(self, other) from numpy.ma.core.MaskedArray
| Divide self into other, and return a new masked array.
|
| __setitem__(self, indx, value) from numpy.ma.core.MaskedArray
| x.__setitem__(i, y) <==> x[i]=y
|
| Set item described by index. If value is masked, masks those
| locations.
|
| __setmask__(self, mask, copy=False) from numpy.ma.core.MaskedArray
| Set the mask.
|
| __setstate__(self, state) from numpy.ma.core.MaskedArray
| Restore the internal state of the masked array, for
| pickling purposes. ``state`` is typically the output of the
| ``__getstate__`` output, and is a 5-tuple:
|
| - class name
| - a tuple giving the shape of the data
| - a typecode for the data
| - a binary string for the data
| - a binary string for the mask.
|
| __str__(self) from numpy.ma.core.MaskedArray
| Return str(self).
|
| __sub__(self, other) from numpy.ma.core.MaskedArray
| Subtract other from self, and return a new masked array.
|
| __truediv__(self, other) from numpy.ma.core.MaskedArray
| Divide other into self, and return a new masked array.
|
| all(self, axis=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns True if all elements evaluate to True.
|
| The output array is masked where all the values along the given axis
| are masked: if the output would have been a scalar and that all the
| values are masked, then the output is `masked`.
|
| Refer to `numpy.all` for full documentation.
|
| See Also
| --------
| numpy.ndarray.all : corresponding function for ndarrays
| numpy.all : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> np.ma.array([1,2,3]).all()
| True
| >>> a = np.ma.array([1,2,3], mask=True)
| >>> (a.all() is np.ma.masked)
| True
|
| anom(self, axis=None, dtype=None) from numpy.ma.core.MaskedArray
| Compute the anomalies (deviations from the arithmetic mean)
| along the given axis.
|
| Returns an array of anomalies, with the same shape as the input and
| where the arithmetic mean is computed along the given axis.
|
| Parameters
| ----------
| axis : int, optional
| Axis over which the anomalies are taken.
| The default is to use the mean of the flattened array as reference.
| dtype : dtype, optional
| Type to use in computing the variance. For arrays of integer type
| the default is float32; for arrays of float types it is the same as
| the array type.
|
| See Also
| --------
| mean : Compute the mean of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([1,2,3])
| >>> a.anom()
| masked_array(data=[-1., 0., 1.],
| mask=False,
| fill_value=1e+20)
|
| any(self, axis=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns True if any of the elements of `a` evaluate to True.
|
| Masked values are considered as False during computation.
|
| Refer to `numpy.any` for full documentation.
|
| See Also
| --------
| numpy.ndarray.any : corresponding function for ndarrays
| numpy.any : equivalent function
|
| argmax(self, axis=None, fill_value=None, out=None, *, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns array of indices of the maximum values along the given axis.
| Masked values are treated as if they had the value fill_value.
|
| Parameters
| ----------
| axis : {None, integer}
| If None, the index is into the flattened array, otherwise along
| the specified axis
| fill_value : scalar or None, optional
| Value used to fill in the masked values. If None, the output of
| maximum_fill_value(self._data) is used instead.
| out : {None, array}, optional
| Array into which the result can be placed. Its type is preserved
| and it must be of the right shape to hold the output.
|
| Returns
| -------
| index_array : {integer_array}
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.arange(6).reshape(2,3)
| >>> a.argmax()
| 5
| >>> a.argmax(0)
| array([1, 1, 1])
| >>> a.argmax(1)
| array([2, 2])
|
| argmin(self, axis=None, fill_value=None, out=None, *, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return array of indices to the minimum values along the given axis.
|
| Parameters
| ----------
| axis : {None, integer}
| If None, the index is into the flattened array, otherwise along
| the specified axis
| fill_value : scalar or None, optional
| Value used to fill in the masked values. If None, the output of
| minimum_fill_value(self._data) is used instead.
| out : {None, array}, optional
| Array into which the result can be placed. Its type is preserved
| and it must be of the right shape to hold the output.
|
| Returns
| -------
| ndarray or scalar
| If multi-dimension input, returns a new ndarray of indices to the
| minimum values along the given axis. Otherwise, returns a scalar
| of index to the minimum values along the given axis.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array(np.arange(4), mask=[1,1,0,0])
| >>> x.shape = (2,2)
| >>> x
| masked_array(
| data=[[--, --],
| [2, 3]],
| mask=[[ True, True],
| [False, False]],
| fill_value=999999)
| >>> x.argmin(axis=0, fill_value=-1)
| array([0, 0])
| >>> x.argmin(axis=0, fill_value=9)
| array([1, 1])
|
| argpartition(self, *args, **kwargs) from numpy.ma.core.MaskedArray
| a.argpartition(kth, axis=-1, kind='introselect', order=None)
|
| Returns the indices that would partition this array.
|
| Refer to `numpy.argpartition` for full documentation.
|
| .. versionadded:: 1.8.0
|
| See Also
| --------
| numpy.argpartition : equivalent function
|
| argsort(self, axis=<no value>, kind=None, order=None, endwith=True, fill_value=None, *, stable=False) from numpy.ma.core.MaskedArray
| Return an ndarray of indices that sort the array along the
| specified axis. Masked values are filled beforehand to
| `fill_value`.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which to sort. If None, the default, the flattened array
| is used.
|
| .. versionchanged:: 1.13.0
| Previously, the default was documented to be -1, but that was
| in error. At some future date, the default will change to -1, as
| originally intended.
| Until then, the axis should be given explicitly when
| ``arr.ndim > 1``, to avoid a FutureWarning.
| kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| The sorting algorithm used.
| order : list, optional
| When `a` is an array with fields defined, this argument specifies
| which fields to compare first, second, etc. Not all fields need be
| specified.
| endwith : {True, False}, optional
| Whether missing values (if any) should be treated as the largest values
| (True) or the smallest values (False)
| When the array contains unmasked values at the same extremes of the
| datatype, the ordering of these values and the masked values is
| undefined.
| fill_value : scalar or None, optional
| Value used internally for the masked values.
| If ``fill_value`` is not None, it supersedes ``endwith``.
| stable : bool, optional
| Only for compatibility with ``np.argsort``. Ignored.
|
| Returns
| -------
| index_array : ndarray, int
| Array of indices that sort `a` along the specified axis.
| In other words, ``a[index_array]`` yields a sorted `a`.
|
| See Also
| --------
| ma.MaskedArray.sort : Describes sorting algorithms used.
| lexsort : Indirect stable sort with multiple keys.
| numpy.ndarray.sort : Inplace sort.
|
| Notes
| -----
| See `sort` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([3,2,1], mask=[False, False, True])
| >>> a
| masked_array(data=[3, 2, --],
| mask=[False, False, True],
| fill_value=999999)
| >>> a.argsort()
| array([1, 0, 2])
|
| compress(self, condition, axis=None, out=None) from numpy.ma.core.MaskedArray
| Return `a` where condition is ``True``.
|
| If condition is a `~ma.MaskedArray`, missing values are considered
| as ``False``.
|
| Parameters
| ----------
| condition : var
| Boolean 1-d array selecting which entries to return. If len(condition)
| is less than the size of a along the axis, then output is truncated
| to length of condition array.
| axis : {None, int}, optional
| Axis along which the operation must be performed.
| out : {None, ndarray}, optional
| Alternative output array in which to place the result. It must have
| the same shape as the expected output but the type will be cast if
| necessary.
|
| Returns
| -------
| result : MaskedArray
| A :class:`~ma.MaskedArray` object.
|
| Notes
| -----
| Please note the difference with :meth:`compressed` !
| The output of :meth:`compress` has a mask, the output of
| :meth:`compressed` does not.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.compress([1, 0, 1])
| masked_array(data=[1, 3],
| mask=[False, False],
| fill_value=999999)
|
| >>> x.compress([1, 0, 1], axis=1)
| masked_array(
| data=[[1, 3],
| [--, --],
| [7, 9]],
| mask=[[False, False],
| [ True, True],
| [False, False]],
| fill_value=999999)
|
| compressed(self) from numpy.ma.core.MaskedArray
| Return all the non-masked data as a 1-D array.
|
| Returns
| -------
| data : ndarray
| A new `ndarray` holding the non-masked data is returned.
|
| Notes
| -----
| The result is **not** a MaskedArray!
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3)
| >>> x.compressed()
| array([0, 1])
| >>> type(x.compressed())
| <class 'numpy.ndarray'>
|
| N-D arrays are compressed to 1-D.
|
| >>> arr = [[1, 2], [3, 4]]
| >>> mask = [[1, 0], [0, 1]]
| >>> x = np.ma.array(arr, mask=mask)
| >>> x.compressed()
| array([2, 3])
|
| copy(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.copy(order='C')
|
| Return a copy of the array.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout of the copy. 'C' means C-order,
| 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| 'C' otherwise. 'K' means match the layout of `a` as closely
| as possible. (Note that this function and :func:`numpy.copy` are very
| similar but have different default values for their order=
| arguments, and this function always passes sub-classes through.)
|
| See also
| --------
| numpy.copy : Similar function with different default behavior
| numpy.copyto
|
| Notes
| -----
| This function is the preferred method for creating an array copy. The
| function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| and will not pass sub-classes through by default.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[1,2,3],[4,5,6]], order='F')
|
| >>> y = x.copy()
|
| >>> x.fill(0)
|
| >>> x
| array([[0, 0, 0],
| [0, 0, 0]])
|
| >>> y
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> y.flags['C_CONTIGUOUS']
| True
|
| For arrays containing Python objects (e.g. dtype=object),
| the copy is a shallow one. The new array will contain the
| same object which may lead to surprises if that object can
| be modified (is mutable):
|
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> b = a.copy()
| >>> b[2][0] = 10
| >>> a
| array([1, 'm', list([10, 3, 4])], dtype=object)
|
| To ensure all elements within an ``object`` array are copied,
| use `copy.deepcopy`:
|
| >>> import copy
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> c = copy.deepcopy(a)
| >>> c[2][0] = 10
| >>> c
| array([1, 'm', list([10, 3, 4])], dtype=object)
| >>> a
| array([1, 'm', list([2, 3, 4])], dtype=object)
|
| count(self, axis=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Count the non-masked elements of the array along the given axis.
|
| Parameters
| ----------
| axis : None or int or tuple of ints, optional
| Axis or axes along which the count is performed.
| The default, None, performs the count over all
| the dimensions of the input array. `axis` may be negative, in
| which case it counts from the last to the first axis.
|
| .. versionadded:: 1.10.0
|
| If this is a tuple of ints, the count is performed on multiple
| axes, instead of a single axis or all the axes as before.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| result : ndarray or scalar
| An array with the same shape as the input array, with the specified
| axis removed. If the array is a 0-d array, or if `axis` is None, a
| scalar is returned.
|
| See Also
| --------
| ma.count_masked : Count masked elements in array or along a given axis.
|
| Examples
| --------
| >>> import numpy.ma as ma
| >>> a = ma.arange(6).reshape((2, 3))
| >>> a[1, :] = ma.masked
| >>> a
| masked_array(
| data=[[0, 1, 2],
| [--, --, --]],
| mask=[[False, False, False],
| [ True, True, True]],
| fill_value=999999)
| >>> a.count()
| 3
|
| When the `axis` keyword is specified an array of appropriate size is
| returned.
|
| >>> a.count(axis=0)
| array([1, 1, 1])
| >>> a.count(axis=1)
| array([3, 0])
|
| cumprod(self, axis=None, dtype=None, out=None) from numpy.ma.core.MaskedArray
| Return the cumulative product of the array elements over the given axis.
|
| Masked values are set to 1 internally during the computation.
| However, their position is saved, and the result will be masked at
| the same locations.
|
| Refer to `numpy.cumprod` for full documentation.
|
| Notes
| -----
| The mask is lost if `out` is not a valid MaskedArray !
|
| Arithmetic is modular when using integer types, and no error is
| raised on overflow.
|
| See Also
| --------
| numpy.ndarray.cumprod : corresponding function for ndarrays
| numpy.cumprod : equivalent function
|
| cumsum(self, axis=None, dtype=None, out=None) from numpy.ma.core.MaskedArray
| Return the cumulative sum of the array elements over the given axis.
|
| Masked values are set to 0 internally during the computation.
| However, their position is saved, and the result will be masked at
| the same locations.
|
| Refer to `numpy.cumsum` for full documentation.
|
| Notes
| -----
| The mask is lost if `out` is not a valid :class:`ma.MaskedArray` !
|
| Arithmetic is modular when using integer types, and no error is
| raised on overflow.
|
| See Also
| --------
| numpy.ndarray.cumsum : corresponding function for ndarrays
| numpy.cumsum : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
| >>> marr.cumsum()
| masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33],
| mask=[False, False, False, True, True, True, False, False,
| False, False],
| fill_value=999999)
|
| diagonal(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.diagonal(offset=0, axis1=0, axis2=1)
|
| Return specified diagonals. In NumPy 1.9 the returned array is a
| read-only view instead of a copy as in previous NumPy versions. In
| a future version the read-only restriction will be removed.
|
| Refer to :func:`numpy.diagonal` for full documentation.
|
| See Also
| --------
| numpy.diagonal : equivalent function
|
| dot(self, b, out=None, strict=False) from numpy.ma.core.MaskedArray
| a.dot(b, out=None)
|
| Masked dot product of two arrays. Note that `out` and `strict` are
| located in different positions than in `ma.dot`. In order to
| maintain compatibility with the functional version, it is
| recommended that the optional arguments be treated as keyword only.
| At some point that may be mandatory.
|
| .. versionadded:: 1.10.0
|
| Parameters
| ----------
| b : masked_array_like
| Inputs array.
| out : masked_array, optional
| Output argument. This must have the exact kind that would be
| returned if it was not used. In particular, it must have the
| right type, must be C-contiguous, and its dtype must be the
| dtype that would be returned for `ma.dot(a,b)`. This is a
| performance feature. Therefore, if these conditions are not
| met, an exception is raised, instead of attempting to be
| flexible.
| strict : bool, optional
| Whether masked data are propagated (True) or set to 0 (False)
| for the computation. Default is False. Propagating the mask
| means that if a masked value appears in a row or column, the
| whole row or column is considered masked.
|
| .. versionadded:: 1.10.2
|
| See Also
| --------
| numpy.ma.dot : equivalent function
|
| filled(self, fill_value=None) from numpy.ma.core.MaskedArray
| Return a copy of self, with masked values filled with a given value.
| **However**, if there are no masked values to fill, self will be
| returned instead as an ndarray.
|
| Parameters
| ----------
| fill_value : array_like, optional
| The value to use for invalid entries. Can be scalar or non-scalar.
| If non-scalar, the resulting ndarray must be broadcastable over
| input array. Default is None, in which case, the `fill_value`
| attribute of the array is used instead.
|
| Returns
| -------
| filled_array : ndarray
| A copy of ``self`` with invalid entries replaced by *fill_value*
| (be it the function argument or the attribute of ``self``), or
| ``self`` itself as an ndarray if there are no invalid entries to
| be replaced.
|
| Notes
| -----
| The result is **not** a MaskedArray!
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
| >>> x.filled()
| array([ 1, 2, -999, 4, -999])
| >>> x.filled(fill_value=1000)
| array([ 1, 2, 1000, 4, 1000])
| >>> type(x.filled())
| <class 'numpy.ndarray'>
|
| Subclassing is preserved. This means that if, e.g., the data part of
| the masked array is a recarray, `filled` returns a recarray:
|
| >>> x = np.array([(-1, 2), (-3, 4)], dtype='i8,i8').view(np.recarray)
| >>> m = np.ma.array(x, mask=[(True, False), (False, True)])
| >>> m.filled()
| rec.array([(999999, 2), ( -3, 999999)],
| dtype=[('f0', '<i8'), ('f1', '<i8')])
|
| flatten(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.flatten(order='C')
|
| Return a copy of the array collapsed into one dimension.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| 'C' means to flatten in row-major (C-style) order.
| 'F' means to flatten in column-major (Fortran-
| style) order. 'A' means to flatten in column-major
| order if `a` is Fortran *contiguous* in memory,
| row-major order otherwise. 'K' means to flatten
| `a` in the order the elements occur in memory.
| The default is 'C'.
|
| Returns
| -------
| y : ndarray
| A copy of the input array, flattened to one dimension.
|
| See Also
| --------
| ravel : Return a flattened array.
| flat : A 1-D flat iterator over the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,2], [3,4]])
| >>> a.flatten()
| array([1, 2, 3, 4])
| >>> a.flatten('F')
| array([1, 3, 2, 4])
|
| get_fill_value = fill_value(self) from numpy.ma.core.MaskedArray
| The filling value of the masked array is a scalar. When setting, None
| will set to a default based on the data type.
|
| Examples
| --------
| >>> import numpy as np
| >>> for dt in [np.int32, np.int64, np.float64, np.complex128]:
| ... np.ma.array([0, 1], dtype=dt).get_fill_value()
| ...
| np.int64(999999)
| np.int64(999999)
| np.float64(1e+20)
| np.complex128(1e+20+0j)
|
| >>> x = np.ma.array([0, 1.], fill_value=-np.inf)
| >>> x.fill_value
| np.float64(-inf)
| >>> x.fill_value = np.pi
| >>> x.fill_value
| np.float64(3.1415926535897931)
|
| Reset to default:
|
| >>> x.fill_value = None
| >>> x.fill_value
| np.float64(1e+20)
|
| get_imag = imag(self) from numpy.ma.core.MaskedArray
| The imaginary part of the masked array.
|
| This property is a view on the imaginary part of this `MaskedArray`.
|
| See Also
| --------
| real
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.imag
| masked_array(data=[1.0, --, 1.6],
| mask=[False, True, False],
| fill_value=1e+20)
|
| get_real = real(self) from numpy.ma.core.MaskedArray
| The real part of the masked array.
|
| This property is a view on the real part of this `MaskedArray`.
|
| See Also
| --------
| imag
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.real
| masked_array(data=[1.0, --, 3.45],
| mask=[False, True, False],
| fill_value=1e+20)
|
| harden_mask(self) from numpy.ma.core.MaskedArray
| Force the mask to hard, preventing unmasking by assignment.
|
| Whether the mask of a masked array is hard or soft is determined by
| its `~ma.MaskedArray.hardmask` property. `harden_mask` sets
| `~ma.MaskedArray.hardmask` to ``True`` (and returns the modified
| self).
|
| See Also
| --------
| ma.MaskedArray.hardmask
| ma.MaskedArray.soften_mask
|
| ids(self) from numpy.ma.core.MaskedArray
| Return the addresses of the data and mask areas.
|
| Parameters
| ----------
| None
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1])
| >>> x.ids()
| (166670640, 166659832) # may vary
|
| If the array has no mask, the address of `nomask` is returned. This address
| is typically not close to the data in memory:
|
| >>> x = np.ma.array([1, 2, 3])
| >>> x.ids()
| (166691080, 3083169284) # may vary
|
| iscontiguous(self) from numpy.ma.core.MaskedArray
| Return a boolean indicating whether the data is contiguous.
|
| Parameters
| ----------
| None
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1, 2, 3])
| >>> x.iscontiguous()
| True
|
| `iscontiguous` returns one of the flags of the masked array:
|
| >>> x.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : True
| OWNDATA : False
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
|
| max(self, axis=None, out=None, fill_value=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the maximum along a given axis.
|
| Parameters
| ----------
| axis : None or int or tuple of ints, optional
| Axis along which to operate. By default, ``axis`` is None and the
| flattened input is used.
| .. versionadded:: 1.7.0
| If this is a tuple of ints, the maximum is selected over multiple
| axes, instead of a single axis or all the axes as before.
| out : array_like, optional
| Alternative output array in which to place the result. Must
| be of the same shape and buffer length as the expected output.
| fill_value : scalar or None, optional
| Value used to fill in the masked values.
| If None, use the output of maximum_fill_value().
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| amax : array_like
| New array holding the result.
| If ``out`` was specified, ``out`` is returned.
|
| See Also
| --------
| ma.maximum_fill_value
| Returns the maximum filling value for a given datatype.
|
| Examples
| --------
| >>> import numpy.ma as ma
| >>> x = [[-1., 2.5], [4., -2.], [3., 0.]]
| >>> mask = [[0, 0], [1, 0], [1, 0]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> masked_x
| masked_array(
| data=[[-1.0, 2.5],
| [--, -2.0],
| [--, 0.0]],
| mask=[[False, False],
| [ True, False],
| [ True, False]],
| fill_value=1e+20)
| >>> ma.max(masked_x)
| 2.5
| >>> ma.max(masked_x, axis=0)
| masked_array(data=[-1.0, 2.5],
| mask=[False, False],
| fill_value=1e+20)
| >>> ma.max(masked_x, axis=1, keepdims=True)
| masked_array(
| data=[[2.5],
| [-2.0],
| [0.0]],
| mask=[[False],
| [False],
| [False]],
| fill_value=1e+20)
| >>> mask = [[1, 1], [1, 1], [1, 1]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> ma.max(masked_x, axis=1)
| masked_array(data=[--, --, --],
| mask=[ True, True, True],
| fill_value=1e+20,
| dtype=float64)
|
| mean(self, axis=None, dtype=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns the average of the array elements along given axis.
|
| Masked entries are ignored, and result elements which are not
| finite will be masked.
|
| Refer to `numpy.mean` for full documentation.
|
| See Also
| --------
| numpy.ndarray.mean : corresponding function for ndarrays
| numpy.mean : Equivalent function
| numpy.ma.average : Weighted average.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([1,2,3], mask=[False, False, True])
| >>> a
| masked_array(data=[1, 2, --],
| mask=[False, False, True],
| fill_value=999999)
| >>> a.mean()
| 1.5
|
| min(self, axis=None, out=None, fill_value=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the minimum along a given axis.
|
| Parameters
| ----------
| axis : None or int or tuple of ints, optional
| Axis along which to operate. By default, ``axis`` is None and the
| flattened input is used.
| .. versionadded:: 1.7.0
| If this is a tuple of ints, the minimum is selected over multiple
| axes, instead of a single axis or all the axes as before.
| out : array_like, optional
| Alternative output array in which to place the result. Must be of
| the same shape and buffer length as the expected output.
| fill_value : scalar or None, optional
| Value used to fill in the masked values.
| If None, use the output of `minimum_fill_value`.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| amin : array_like
| New array holding the result.
| If ``out`` was specified, ``out`` is returned.
|
| See Also
| --------
| ma.minimum_fill_value
| Returns the minimum filling value for a given datatype.
|
| Examples
| --------
| >>> import numpy.ma as ma
| >>> x = [[1., -2., 3.], [0.2, -0.7, 0.1]]
| >>> mask = [[1, 1, 0], [0, 0, 1]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> masked_x
| masked_array(
| data=[[--, --, 3.0],
| [0.2, -0.7, --]],
| mask=[[ True, True, False],
| [False, False, True]],
| fill_value=1e+20)
| >>> ma.min(masked_x)
| -0.7
| >>> ma.min(masked_x, axis=-1)
| masked_array(data=[3.0, -0.7],
| mask=[False, False],
| fill_value=1e+20)
| >>> ma.min(masked_x, axis=0, keepdims=True)
| masked_array(data=[[0.2, -0.7, 3.0]],
| mask=[[False, False, False]],
| fill_value=1e+20)
| >>> mask = [[1, 1, 1,], [1, 1, 1]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> ma.min(masked_x, axis=0)
| masked_array(data=[--, --, --],
| mask=[ True, True, True],
| fill_value=1e+20,
| dtype=float64)
|
| nonzero(self) from numpy.ma.core.MaskedArray
| Return the indices of unmasked elements that are not zero.
|
| Returns a tuple of arrays, one for each dimension, containing the
| indices of the non-zero elements in that dimension. The corresponding
| non-zero values can be obtained with::
|
| a[a.nonzero()]
|
| To group the indices by element, rather than dimension, use
| instead::
|
| np.transpose(a.nonzero())
|
| The result of this is always a 2d array, with a row for each non-zero
| element.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| tuple_of_arrays : tuple
| Indices of elements that are non-zero.
|
| See Also
| --------
| numpy.nonzero :
| Function operating on ndarrays.
| flatnonzero :
| Return indices that are non-zero in the flattened version of the input
| array.
| numpy.ndarray.nonzero :
| Equivalent ndarray method.
| count_nonzero :
| Counts the number of non-zero elements in the input array.
|
| Examples
| --------
| >>> import numpy as np
| >>> import numpy.ma as ma
| >>> x = ma.array(np.eye(3))
| >>> x
| masked_array(
| data=[[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]],
| mask=False,
| fill_value=1e+20)
| >>> x.nonzero()
| (array([0, 1, 2]), array([0, 1, 2]))
|
| Masked elements are ignored.
|
| >>> x[1, 1] = ma.masked
| >>> x
| masked_array(
| data=[[1.0, 0.0, 0.0],
| [0.0, --, 0.0],
| [0.0, 0.0, 1.0]],
| mask=[[False, False, False],
| [False, True, False],
| [False, False, False]],
| fill_value=1e+20)
| >>> x.nonzero()
| (array([0, 2]), array([0, 2]))
|
| Indices can also be grouped by element.
|
| >>> np.transpose(x.nonzero())
| array([[0, 0],
| [2, 2]])
|
| 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, ma.nonzero(a > 3)
| yields the indices of the `a` where the condition is true.
|
| >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
| >>> a > 3
| masked_array(
| data=[[False, False, False],
| [ True, True, True],
| [ True, True, True]],
| mask=False,
| fill_value=True)
| >>> ma.nonzero(a > 3)
| (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
|
| The ``nonzero`` method of the condition array can also be called.
|
| >>> (a > 3).nonzero()
| (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
|
| partition(self, *args, **kwargs) from numpy.ma.core.MaskedArray
| a.partition(kth, axis=-1, kind='introselect', order=None)
|
| Partially sorts the elements in the array 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. In the output array, all elements smaller than the k-th element
| are located to the left of this element and all equal or greater are
| located to its right. The ordering of the elements in the two partitions
| on the either side of the k-th element in the output array is undefined.
|
| .. versionadded:: 1.8.0
|
| Parameters
| ----------
| kth : int or sequence of ints
| Element index to partition by. The kth element value 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 kth it will partition all elements
| indexed by kth of them into their sorted position at once.
|
| .. deprecated:: 1.22.0
| Passing booleans as index is deprecated.
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'introselect'}, optional
| Selection algorithm. Default is 'introselect'.
| order : str 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, and not all fields need to be specified,
| but unspecified fields will still be used, in the order in which
| they come up in the dtype, to break ties.
|
| See Also
| --------
| numpy.partition : Return a partitioned copy of an array.
| argpartition : Indirect partition.
| sort : Full sort.
|
| Notes
| -----
| See ``np.partition`` for notes on the different algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([3, 4, 2, 1])
| >>> a.partition(3)
| >>> a
| array([2, 1, 3, 4]) # may vary
|
| >>> a.partition((1, 3))
| >>> a
| array([1, 2, 3, 4])
|
| prod(self, axis=None, dtype=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the product of the array elements over the given axis.
|
| Masked elements are set to 1 internally for computation.
|
| Refer to `numpy.prod` for full documentation.
|
| Notes
| -----
| Arithmetic is modular when using integer types, and no error is raised
| on overflow.
|
| See Also
| --------
| numpy.ndarray.prod : corresponding function for ndarrays
| numpy.prod : equivalent function
|
| product = prod(self, axis=None, dtype=None, out=None, keepdims=<no value>)
|
| ptp(self, axis=None, out=None, fill_value=None, keepdims=False) from numpy.ma.core.MaskedArray
| Return (maximum - minimum) along the given dimension
| (i.e. peak-to-peak value).
|
| .. warning::
| `ptp` preserves the data type of the array. This means the
| return value for an input of signed integers with n bits
| (e.g. `np.int8`, `np.int16`, etc) is also a signed integer
| with n bits. In that case, peak-to-peak values greater than
| ``2**(n-1)-1`` will be returned as negative values. An example
| with a work-around is shown below.
|
| Parameters
| ----------
| axis : {None, int}, optional
| Axis along which to find the peaks. If None (default) the
| flattened array is used.
| out : {None, array_like}, optional
| Alternative output array in which to place the result. It must
| have the same shape and buffer length as the expected output
| but the type will be cast if necessary.
| fill_value : scalar or None, optional
| Value used to fill in the masked values.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| ptp : ndarray.
| A new array holding the result, unless ``out`` was
| specified, in which case a reference to ``out`` is returned.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.MaskedArray([[4, 9, 2, 10],
| ... [6, 9, 7, 12]])
|
| >>> x.ptp(axis=1)
| masked_array(data=[8, 6],
| mask=False,
| fill_value=999999)
|
| >>> x.ptp(axis=0)
| masked_array(data=[2, 0, 5, 2],
| mask=False,
| fill_value=999999)
|
| >>> x.ptp()
| 10
|
| This example shows that a negative value can be returned when
| the input is an array of signed integers.
|
| >>> y = np.ma.MaskedArray([[1, 127],
| ... [0, 127],
| ... [-1, 127],
| ... [-2, 127]], dtype=np.int8)
| >>> y.ptp(axis=1)
| masked_array(data=[ 126, 127, -128, -127],
| mask=False,
| fill_value=np.int64(999999),
| dtype=int8)
|
| A work-around is to use the `view()` method to view the result as
| unsigned integers with the same bit width:
|
| >>> y.ptp(axis=1).view(np.uint8)
| masked_array(data=[126, 127, 128, 129],
| mask=False,
| fill_value=np.int64(999999),
| dtype=uint8)
|
| put(self, indices, values, mode='raise') from numpy.ma.core.MaskedArray
| Set storage-indexed locations to corresponding values.
|
| Sets self._data.flat[n] = values[n] for each n in indices.
| If `values` is shorter than `indices` then it will repeat.
| If `values` has some masked values, the initial mask is updated
| in consequence, else the corresponding values are unmasked.
|
| Parameters
| ----------
| indices : 1-D array_like
| Target indices, interpreted as integers.
| values : array_like
| Values to place in self._data copy at target indices.
| mode : {'raise', 'wrap', 'clip'}, optional
| Specifies how out-of-bounds indices will behave.
| 'raise' : raise an error.
| 'wrap' : wrap around.
| 'clip' : clip to the range.
|
| Notes
| -----
| `values` can be a scalar or length 1 array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.put([0,4,8],[10,20,30])
| >>> x
| masked_array(
| data=[[10, --, 3],
| [--, 20, --],
| [7, --, 30]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
|
| >>> x.put(4,999)
| >>> x
| masked_array(
| data=[[10, --, 3],
| [--, 999, --],
| [7, --, 30]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
|
| ravel(self, order='C') from numpy.ma.core.MaskedArray
| Returns a 1D version of self, as a view.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| The elements of `a` are read using this index order. 'C' means to
| index the elements in C-like order, with the last axis index
| changing fastest, back to the first axis index changing slowest.
| 'F' means to index the elements in Fortran-like index order, with
| the first index changing fastest, and the last index changing
| slowest. Note that the 'C' and 'F' options take no account of the
| memory layout of the underlying array, and only refer to the order
| of axis indexing. 'A' means to read the elements in Fortran-like
| index order if `m` is Fortran *contiguous* in memory, C-like order
| otherwise. 'K' means to read the elements in the order they occur
| in memory, except for reversing the data when strides are negative.
| By default, 'C' index order is used.
| (Masked arrays currently use 'A' on the data when 'K' is passed.)
|
| Returns
| -------
| MaskedArray
| Output view is of shape ``(self.size,)`` (or
| ``(np.ma.product(self.shape),)``).
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.ravel()
| masked_array(data=[1, --, 3, --, 5, --, 7, --, 9],
| mask=[False, True, False, True, False, True, False, True,
| False],
| fill_value=999999)
|
| repeat(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.repeat(repeats, axis=None)
|
| Repeat elements of an array.
|
| Refer to `numpy.repeat` for full documentation.
|
| See Also
| --------
| numpy.repeat : equivalent function
|
| reshape(self, *s, **kwargs) from numpy.ma.core.MaskedArray
| Give a new shape to the array without changing its data.
|
| Returns a masked array containing the same data, but with a new shape.
| The result is a view on the original array; if this is not possible, a
| ValueError is raised.
|
| Parameters
| ----------
| shape : int or tuple of ints
| The new shape should be compatible with the original shape. If an
| integer is supplied, then the result will be a 1-D array of that
| length.
| order : {'C', 'F'}, optional
| Determines whether the array data should be viewed as in C
| (row-major) or FORTRAN (column-major) order.
|
| Returns
| -------
| reshaped_array : array
| A new view on the array.
|
| See Also
| --------
| reshape : Equivalent function in the masked array module.
| numpy.ndarray.reshape : Equivalent method on ndarray object.
| numpy.reshape : Equivalent function in the NumPy module.
|
| Notes
| -----
| The reshaping operation cannot guarantee that a copy will not be made,
| to modify the shape in place, use ``a.shape = s``
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1])
| >>> x
| masked_array(
| data=[[--, 2],
| [3, --]],
| mask=[[ True, False],
| [False, True]],
| fill_value=999999)
| >>> x = x.reshape((4,1))
| >>> x
| masked_array(
| data=[[--],
| [2],
| [3],
| [--]],
| mask=[[ True],
| [False],
| [False],
| [ True]],
| fill_value=999999)
|
| resize(self, newshape, refcheck=True, order=False) from numpy.ma.core.MaskedArray
| .. warning::
|
| This method does nothing, except raise a ValueError exception. A
| masked array does not own its data and therefore cannot safely be
| resized in place. Use the `numpy.ma.resize` function instead.
|
| This method is difficult to implement safely and may be deprecated in
| future releases of NumPy.
|
| round(self, decimals=0, out=None) from numpy.ma.core.MaskedArray
| Return each element rounded to the given number of decimals.
|
| Refer to `numpy.around` for full documentation.
|
| See Also
| --------
| numpy.ndarray.round : corresponding function for ndarrays
| numpy.around : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> import numpy.ma as ma
| >>> x = ma.array([1.35, 2.5, 1.5, 1.75, 2.25, 2.75],
| ... mask=[0, 0, 0, 1, 0, 0])
| >>> ma.round(x)
| masked_array(data=[1.0, 2.0, 2.0, --, 2.0, 3.0],
| mask=[False, False, False, True, False, False],
| fill_value=1e+20)
|
| set_fill_value = fill_value(self, value=None) from numpy.ma.core.MaskedArray
|
| shrink_mask(self) from numpy.ma.core.MaskedArray
| Reduce a mask to nomask when possible.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| None
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4)
| >>> x.mask
| array([[False, False],
| [False, False]])
| >>> x.shrink_mask()
| masked_array(
| data=[[1, 2],
| [3, 4]],
| mask=False,
| fill_value=999999)
| >>> x.mask
| False
|
| soften_mask(self) from numpy.ma.core.MaskedArray
| Force the mask to soft (default), allowing unmasking by assignment.
|
| Whether the mask of a masked array is hard or soft is determined by
| its `~ma.MaskedArray.hardmask` property. `soften_mask` sets
| `~ma.MaskedArray.hardmask` to ``False`` (and returns the modified
| self).
|
| See Also
| --------
| ma.MaskedArray.hardmask
| ma.MaskedArray.harden_mask
|
| sort(self, axis=-1, kind=None, order=None, endwith=True, fill_value=None, *, stable=False) from numpy.ma.core.MaskedArray
| Sort the array, in-place
|
| Parameters
| ----------
| a : array_like
| Array to be sorted.
| axis : int, 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 : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| The sorting algorithm used.
| order : list, optional
| When `a` is a structured array, this argument specifies which fields
| to compare first, second, and so on. This list does not need to
| include all of the fields.
| endwith : {True, False}, optional
| Whether missing values (if any) should be treated as the largest values
| (True) or the smallest values (False)
| When the array contains unmasked values sorting at the same extremes of the
| datatype, the ordering of these values and the masked values is
| undefined.
| fill_value : scalar or None, optional
| Value used internally for the masked values.
| If ``fill_value`` is not None, it supersedes ``endwith``.
| stable : bool, optional
| Only for compatibility with ``np.sort``. Ignored.
|
| Returns
| -------
| sorted_array : ndarray
| Array of the same type and shape as `a`.
|
| See Also
| --------
| numpy.ndarray.sort : Method to sort an array in-place.
| argsort : Indirect sort.
| lexsort : Indirect stable sort on multiple keys.
| searchsorted : Find elements in a sorted array.
|
| Notes
| -----
| See ``sort`` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
| >>> # Default
| >>> a.sort()
| >>> a
| masked_array(data=[1, 3, 5, --, --],
| mask=[False, False, False, True, True],
| fill_value=999999)
|
| >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
| >>> # Put missing values in the front
| >>> a.sort(endwith=False)
| >>> a
| masked_array(data=[--, --, 1, 3, 5],
| mask=[ True, True, False, False, False],
| fill_value=999999)
|
| >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
| >>> # fill_value takes over endwith
| >>> a.sort(endwith=False, fill_value=3)
| >>> a
| masked_array(data=[1, --, --, 3, 5],
| mask=[False, True, True, False, False],
| fill_value=999999)
|
| squeeze(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.squeeze(axis=None)
|
| Remove axes of length one from `a`.
|
| Refer to `numpy.squeeze` for full documentation.
|
| See Also
| --------
| numpy.squeeze : equivalent function
|
| std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, mean=<no value>) from numpy.ma.core.MaskedArray
| Returns the standard deviation of the array elements along given axis.
|
| Masked entries are ignored.
|
| Refer to `numpy.std` for full documentation.
|
| See Also
| --------
| numpy.ndarray.std : corresponding function for ndarrays
| numpy.std : Equivalent function
|
| sum(self, axis=None, dtype=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the sum of the array elements over the given axis.
|
| Masked elements are set to 0 internally.
|
| Refer to `numpy.sum` for full documentation.
|
| See Also
| --------
| numpy.ndarray.sum : corresponding function for ndarrays
| numpy.sum : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.sum()
| 25
| >>> x.sum(axis=1)
| masked_array(data=[4, 5, 16],
| mask=[False, False, False],
| fill_value=999999)
| >>> x.sum(axis=0)
| masked_array(data=[8, 5, 12],
| mask=[False, False, False],
| fill_value=999999)
| >>> print(type(x.sum(axis=0, dtype=np.int64)[0]))
| <class 'numpy.int64'>
|
| swapaxes(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.swapaxes(axis1, axis2)
|
| Return a view of the array with `axis1` and `axis2` interchanged.
|
| Refer to `numpy.swapaxes` for full documentation.
|
| See Also
| --------
| numpy.swapaxes : equivalent function
|
| take(self, indices, axis=None, out=None, mode='raise') from numpy.ma.core.MaskedArray
|
| tobytes(self, fill_value=None, order='C') from numpy.ma.core.MaskedArray
| Return the array data as a string containing the raw bytes in the array.
|
| The array is filled with a fill value before the string conversion.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| fill_value : scalar, optional
| Value used to fill in the masked values. Default is None, in which
| case `MaskedArray.fill_value` is used.
| order : {'C','F','A'}, optional
| Order of the data item in the copy. Default is 'C'.
|
| - 'C' -- C order (row major).
| - 'F' -- Fortran order (column major).
| - 'A' -- Any, current order of array.
| - None -- Same as 'A'.
|
| See Also
| --------
| numpy.ndarray.tobytes
| tolist, tofile
|
| Notes
| -----
| As for `ndarray.tobytes`, information about the shape, dtype, etc.,
| but also about `fill_value`, will be lost.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
| >>> x.tobytes()
| b'\x01\x00\x00\x00\x00\x00\x00\x00?B\x0f\x00\x00\x00\x00\x00?B\x0f\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00'
|
| tofile(self, fid, sep='', format='%s') from numpy.ma.core.MaskedArray
| Save a masked array to a file in binary format.
|
| .. warning::
| This function is not implemented yet.
|
| Raises
| ------
| NotImplementedError
| When `tofile` is called.
|
| toflex(self) from numpy.ma.core.MaskedArray
| Transforms a masked array into a flexible-type array.
|
| The flexible type array that is returned will have two fields:
|
| * the ``_data`` field stores the ``_data`` part of the array.
| * the ``_mask`` field stores the ``_mask`` part of the array.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| record : ndarray
| A new flexible-type `ndarray` with two fields: the first element
| containing a value, the second element containing the corresponding
| mask boolean. The returned record shape matches self.shape.
|
| Notes
| -----
| A side-effect of transforming a masked array into a flexible `ndarray` is
| that meta information (``fill_value``, ...) will be lost.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.toflex()
| array([[(1, False), (2, True), (3, False)],
| [(4, True), (5, False), (6, True)],
| [(7, False), (8, True), (9, False)]],
| dtype=[('_data', '<i8'), ('_mask', '?')])
|
| tolist(self, fill_value=None) from numpy.ma.core.MaskedArray
| Return the data portion of the masked array as a hierarchical Python list.
|
| Data items are converted to the nearest compatible Python type.
| Masked values are converted to `fill_value`. If `fill_value` is None,
| the corresponding entries in the output list will be ``None``.
|
| Parameters
| ----------
| fill_value : scalar, optional
| The value to use for invalid entries. Default is None.
|
| Returns
| -------
| result : list
| The Python list representation of the masked array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4)
| >>> x.tolist()
| [[1, None, 3], [None, 5, None], [7, None, 9]]
| >>> x.tolist(-999)
| [[1, -999, 3], [-999, 5, -999], [7, -999, 9]]
|
| torecords = toflex(self)
|
| tostring(self, fill_value=None, order='C') from numpy.ma.core.MaskedArray
| A compatibility alias for `tobytes`, with exactly the same behavior.
|
| Despite its name, it returns `bytes` not `str`\ s.
|
| .. deprecated:: 1.19.0
|
| trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None) from numpy.ma.core.MaskedArray
| a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
|
| Return the sum along diagonals of the array.
|
| Refer to `numpy.trace` for full documentation.
|
| See Also
| --------
| numpy.trace : equivalent function
|
| transpose(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.transpose(*axes)
|
| Returns a view of the array with axes transposed.
|
| Refer to `numpy.transpose` for full documentation.
|
| Parameters
| ----------
| axes : None, tuple of ints, or `n` ints
|
| * None or no argument: reverses the order of the axes.
|
| * tuple of ints: `i` in the `j`-th place in the tuple means that the
| array's `i`-th axis becomes the transposed array's `j`-th axis.
|
| * `n` ints: same as an n-tuple of the same ints (this form is
| intended simply as a "convenience" alternative to the tuple form).
|
| Returns
| -------
| p : ndarray
| View of the array with its axes suitably permuted.
|
| See Also
| --------
| transpose : Equivalent function.
| ndarray.T : Array property returning the array transposed.
| ndarray.reshape : Give a new shape to an array without changing its data.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.transpose()
| array([[1, 3],
| [2, 4]])
| >>> a.transpose((1, 0))
| array([[1, 3],
| [2, 4]])
| >>> a.transpose(1, 0)
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.transpose()
| array([1, 2, 3, 4])
|
| unshare_mask(self) from numpy.ma.core.MaskedArray
| Copy the mask and set the `sharedmask` flag to ``False``.
|
| Whether the mask is shared between masked arrays can be seen from
| the `sharedmask` property. `unshare_mask` ensures the mask is not
| shared. A copy of the mask is only made if it was shared.
|
| See Also
| --------
| sharedmask
|
| var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, mean=<no value>) from numpy.ma.core.MaskedArray
| Compute the variance along the specified axis.
|
| 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.
|
| Parameters
| ----------
| a : array_like
| Array containing numbers whose variance is desired. If `a` is not an
| array, a conversion is attempted.
| axis : None or int or tuple of ints, optional
| Axis or axes along which the variance is computed. The default is to
| compute the variance of the flattened array.
|
| .. versionadded:: 1.7.0
|
| If this is a tuple of ints, a variance is performed over multiple axes,
| instead of a single axis or all the axes as before.
| dtype : data-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.
| out : ndarray, 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.
| ddof : {int, float}, optional
| "Delta Degrees of Freedom": the divisor used in the calculation is
| ``N - ddof``, where ``N`` represents the number of elements. By
| default `ddof` is zero. See notes for details about use of `ddof`.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the input array.
|
| If the default value is passed, then `keepdims` will not be
| passed through to the `var` method of sub-classes of
| `ndarray`, however any non-default value will be. If the
| sub-class' method does not implement `keepdims` any
| exceptions will be raised.
| where : array_like of bool, optional
| Elements to include in the variance. See `~numpy.ufunc.reduce` for
| details.
|
| .. versionadded:: 1.20.0
|
| mean : array like, optional
| Provide the mean to prevent its recalculation. The mean should have
| a shape as if it was calculated with ``keepdims=True``.
| The axis for the calculation of the mean should be the same as used in
| the call to this var function.
|
| .. versionadded:: 1.26.0
|
| correction : {int, float}, optional
| Array API compatible name for the ``ddof`` parameter. Only one of them
| can be provided at the same time.
|
| .. versionadded:: 2.0.0
|
| Returns
| -------
| variance : ndarray, see dtype parameter above
| If ``out=None``, returns a new array containing the variance;
| otherwise, a reference to the output array is returned.
|
| See Also
| --------
| std, mean, nanmean, nanstd, nanvar
| :ref:`ufuncs-output-type`
|
| Notes
| -----
| There are several common variants of the array variance calculation.
| Assuming the input `a` is a one-dimensional NumPy array and ``mean`` is
| either provided as an argument or computed as ``a.mean()``, NumPy
| computes the variance of an array as::
|
| N = len(a)
| d2 = abs(a - mean)**2 # abs is for complex `a`
| var = d2.sum() / (N - ddof) # note use of `ddof`
|
| Different values of the argument `ddof` are useful in different
| contexts. NumPy's default ``ddof=0`` corresponds with the expression:
|
| .. math::
|
| \frac{\sum_i{|a_i - \bar{a}|^2 }}{N}
|
| which is sometimes called the "population variance" in the field of
| statistics because it applies the definition of variance to `a` as if `a`
| were a complete population of possible observations.
|
| Many other libraries define the variance of an array differently, e.g.:
|
| .. math::
|
| \frac{\sum_i{|a_i - \bar{a}|^2}}{N - 1}
|
| In statistics, the resulting quantity is sometimed called the "sample
| variance" because if `a` is a random sample from a larger population,
| this calculation provides an unbiased estimate of the variance of the
| population. The use of :math:`N-1` in the denominator is often called
| "Bessel's correction" because it corrects for bias (toward lower values)
| in the variance estimate introduced when the sample mean of `a` is used
| in place of the true mean of the population. For this quantity, use
| ``ddof=1``.
|
| 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.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> np.var(a)
| 1.25
| >>> np.var(a, axis=0)
| array([1., 1.])
| >>> np.var(a, axis=1)
| array([0.25, 0.25])
|
| In single precision, var() can be inaccurate:
|
| >>> a = np.zeros((2, 512*512), dtype=np.float32)
| >>> a[0, :] = 1.0
| >>> a[1, :] = 0.1
| >>> np.var(a)
| 0.20250003
|
| Computing the variance in float64 is more accurate:
|
| >>> np.var(a, dtype=np.float64)
| 0.20249999932944759 # may vary
| >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
| 0.2025
|
| Specifying a where argument:
|
| >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
| >>> np.var(a)
| 6.833333333333333 # may vary
| >>> np.var(a, where=[[True], [True], [False]])
| 4.0
|
| Using the mean keyword to save computation time:
|
| >>> import numpy as np
| >>> from timeit import timeit
| >>>
| >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
| >>> mean = np.mean(a, axis=1, keepdims=True)
| >>>
| >>> g = globals()
| >>> n = 10000
| >>> t1 = timeit("var = np.var(a, axis=1, mean=mean)", globals=g, number=n)
| >>> t2 = timeit("var = np.var(a, axis=1)", globals=g, number=n)
| >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
| #doctest: +SKIP
| Percentage execution time saved 32%
|
| view(self, dtype=None, type=None, fill_value=None) from numpy.ma.core.MaskedArray
| Return a view of the MaskedArray data.
|
| Parameters
| ----------
| dtype : data-type or ndarray sub-class, optional
| Data-type descriptor of the returned view, e.g., float32 or int16.
| The default, None, results in the view having the same data-type
| as `a`. As with ``ndarray.view``, dtype can also be specified as
| an ndarray sub-class, which then specifies the type of the
| returned object (this is equivalent to setting the ``type``
| parameter).
| type : Python type, optional
| Type of the returned view, either ndarray or a subclass. The
| default None results in type preservation.
| fill_value : scalar, optional
| The value to use for invalid entries (None by default).
| If None, then this argument is inferred from the passed `dtype`, or
| in its absence the original array, as discussed in the notes below.
|
| See Also
| --------
| numpy.ndarray.view : Equivalent method on ndarray object.
|
| Notes
| -----
|
| ``a.view()`` is used two different ways:
|
| ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| of the array's memory with a different data-type. This can cause a
| reinterpretation of the bytes of memory.
|
| ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| returns an instance of `ndarray_subclass` that looks at the same array
| (same shape, dtype, etc.) This does not cause a reinterpretation of the
| memory.
|
| If `fill_value` is not specified, but `dtype` is specified (and is not
| an ndarray sub-class), the `fill_value` of the MaskedArray will be
| reset. If neither `fill_value` nor `dtype` are specified (or if
| `dtype` is an ndarray sub-class), then the fill value is preserved.
| Finally, if `fill_value` is specified, but `dtype` is not, the fill
| value is set to the specified value.
|
| For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| bytes per entry than the previous dtype (for example, converting a
| regular array to a structured array), then the behavior of the view
| cannot be predicted just from the superficial appearance of ``a`` (shown
| by ``print(a)``). It also depends on exactly how ``a`` is stored in
| memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus
| defined as a slice or transpose, etc., the view may give different
| results.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, data=None, mask=np.False_, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, keep_mask=True, hard_mask=None, shrink=True, order=None) from numpy.ma.core.MaskedArray
| Create a new masked array from scratch.
|
| Notes
| -----
| A masked array can also be created by taking a .view(MaskedArray).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| T
|
| baseclass
| Class of the underlying data (read-only).
|
| data
| Returns the underlying data, as a view of the masked array.
|
| If the underlying data is a subclass of :class:`numpy.ndarray`, it is
| returned as such.
|
| >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
| >>> x.data
| matrix([[1, 2],
| [3, 4]])
|
| The type of the data can be accessed through the :attr:`baseclass`
| attribute.
|
| hardmask
| Specifies whether values can be unmasked through assignments.
|
| By default, assigning definite values to masked array entries will
| unmask them. When `hardmask` is ``True``, the mask will not change
| through assignments.
|
| See Also
| --------
| ma.MaskedArray.harden_mask
| ma.MaskedArray.soften_mask
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(10)
| >>> m = np.ma.masked_array(x, x>5)
| >>> assert not m.hardmask
|
| Since `m` has a soft mask, assigning an element value unmasks that
| element:
|
| >>> m[8] = 42
| >>> m
| masked_array(data=[0, 1, 2, 3, 4, 5, --, --, 42, --],
| mask=[False, False, False, False, False, False,
| True, True, False, True],
| fill_value=999999)
|
| After hardening, the mask is not affected by assignments:
|
| >>> hardened = np.ma.harden_mask(m)
| >>> assert m.hardmask and hardened is m
| >>> m[:] = 23
| >>> m
| masked_array(data=[23, 23, 23, 23, 23, 23, --, --, 23, --],
| mask=[False, False, False, False, False, False,
| True, True, False, True],
| fill_value=999999)
|
| imag
| The imaginary part of the masked array.
|
| This property is a view on the imaginary part of this `MaskedArray`.
|
| See Also
| --------
| real
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.imag
| masked_array(data=[1.0, --, 1.6],
| mask=[False, True, False],
| fill_value=1e+20)
|
| mT
| Return the matrix-transpose of the masked array.
|
| The matrix transpose is the transpose of the last two dimensions, even
| if the array is of higher dimension.
|
| .. versionadded:: 2.0
|
| Returns
| -------
| result: MaskedArray
| The masked array with the last two dimensions transposed
|
| Raises
| ------
| ValueError
| If the array is of dimension less than 2.
|
| See Also
| --------
| ndarray.mT:
| Equivalent method for arrays
|
| real
| The real part of the masked array.
|
| This property is a view on the real part of this `MaskedArray`.
|
| See Also
| --------
| imag
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.real
| masked_array(data=[1.0, --, 3.45],
| mask=[False, True, False],
| fill_value=1e+20)
|
| sharedmask
| Share status of the mask (read-only).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| dtype
| Data-type of the array's elements.
|
| .. warning::
|
| Setting ``arr.dtype`` is discouraged and may be deprecated in the
| future. Setting will replace the ``dtype`` without modifying the
| memory (see also `ndarray.view` and `ndarray.astype`).
|
| Parameters
| ----------
| None
|
| Returns
| -------
| d : numpy dtype object
|
| See Also
| --------
| ndarray.astype : Cast the values contained in the array to a new data-type.
| ndarray.view : Create a view of the same data but a different data-type.
| numpy.dtype
|
| Examples
| --------
| >>> x
| array([[0, 1],
| [2, 3]])
| >>> x.dtype
| dtype('int32')
| >>> type(x.dtype)
| <type 'numpy.dtype'>
|
| fill_value
| The filling value of the masked array is a scalar. When setting, None
| will set to a default based on the data type.
|
| Examples
| --------
| >>> import numpy as np
| >>> for dt in [np.int32, np.int64, np.float64, np.complex128]:
| ... np.ma.array([0, 1], dtype=dt).get_fill_value()
| ...
| np.int64(999999)
| np.int64(999999)
| np.float64(1e+20)
| np.complex128(1e+20+0j)
|
| >>> x = np.ma.array([0, 1.], fill_value=-np.inf)
| >>> x.fill_value
| np.float64(-inf)
| >>> x.fill_value = np.pi
| >>> x.fill_value
| np.float64(3.1415926535897931)
|
| Reset to default:
|
| >>> x.fill_value = None
| >>> x.fill_value
| np.float64(1e+20)
|
| flat
| Return a flat iterator, or set a flattened version of self to value.
|
| mask
| Current mask.
|
| recordmask
| Get or set the mask of the array if it has no named fields. For
| structured arrays, returns a ndarray of booleans where entries are
| ``True`` if **all** the fields are masked, ``False`` otherwise:
|
| >>> x = np.ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
| ... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)],
| ... dtype=[('a', int), ('b', int)])
| >>> x.recordmask
| array([False, False, True, False, False])
|
| shape
| Tuple of array dimensions.
|
| The shape property is usually used to get the current shape of an array,
| but may also be used to reshape the array in-place by assigning a tuple of
| array dimensions to it. As with `numpy.reshape`, one of the new shape
| dimensions can be -1, in which case its value is inferred from the size of
| the array and the remaining dimensions. Reshaping an array in-place will
| fail if a copy is required.
|
| .. warning::
|
| Setting ``arr.shape`` is discouraged and may be deprecated in the
| future. Using `ndarray.reshape` is the preferred approach.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3, 4])
| >>> x.shape
| (4,)
| >>> y = np.zeros((2, 3, 4))
| >>> y.shape
| (2, 3, 4)
| >>> y.shape = (3, 8)
| >>> y
| array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| >>> y.shape = (3, 6)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: total size of new array must be unchanged
| >>> np.zeros((4,2))[::2].shape = (-1,)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| AttributeError: Incompatible shape for in-place modification. Use
| `.reshape()` to make a copy with the desired shape.
|
| See Also
| --------
| numpy.shape : Equivalent getter function.
| numpy.reshape : Function similar to setting ``shape``.
| ndarray.reshape : Method similar to setting ``shape``.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __array_priority__ = 15
|
| __hash__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.ndarray:
|
| __abs__(self, /)
| abs(self)
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| a.__array__([dtype], *, copy=None)
|
| For ``dtype`` parameter it returns a new reference to self if
| ``dtype`` is not given or it matches array's data type.
| A new array of provided data type is returned if ``dtype``
| is different from the current data type of the array.
| For ``copy`` parameter it returns a new reference to self if
| ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| parameter. The method returns a new array for ``copy=True``, regardless of
| ``dtype`` parameter.
|
| A more detailed explanation of the ``__array__`` interface
| can be found in :ref:`dunder_array.interface`.
|
| __array_function__(...)
|
| __array_namespace__(...)
|
| __array_ufunc__(...)
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __complex__(...)
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __copy__(...)
| a.__copy__()
|
| Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
|
| Equivalent to ``a.copy(order='K')``.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __dlpack__(...)
| a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
|
| DLPack Protocol: Part of the Array API.
|
| __dlpack_device__(...)
| a.__dlpack_device__()
|
| DLPack Protocol: Part of the Array API.
|
| __format__(...)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __ilshift__(self, value, /)
| Return self<<=value.
|
| __imatmul__(self, value, /)
| Return self@=value.
|
| __imod__(self, value, /)
| Return self%=value.
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __invert__(self, /)
| ~self
|
| __ior__(self, value, /)
| Return self|=value.
|
| __irshift__(self, value, /)
| Return self>>=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __len__(self, /)
| Return len(self).
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __matmul__(self, value, /)
| Return self@value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce_ex__(...)
| Helper for pickle.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmatmul__(self, value, /)
| Return value@self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __xor__(self, value, /)
| Return self^value.
|
| astype(...)
| a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
|
| Copy of the array, cast to a specified type.
|
| Parameters
| ----------
| dtype : str or dtype
| Typecode or data-type to which the array is cast.
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout order of the result.
| '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.
| Default is 'K'.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'unsafe'
| for backwards compatibility.
|
| * '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.
| subok : bool, optional
| If True, then sub-classes will be passed-through (default), otherwise
| the returned array will be forced to be a base-class array.
| copy : bool, optional
| By default, astype always returns a newly allocated array. If this
| is set to false, and the `dtype`, `order`, and `subok`
| requirements are satisfied, the input array is returned instead
| of a copy.
|
| Returns
| -------
| arr_t : ndarray
| Unless `copy` is False and the other conditions for returning the input
| array are satisfied (see description for `copy` input parameter), `arr_t`
| is a new array of the same shape as the input array, with dtype, order
| given by `dtype`, `order`.
|
| Notes
| -----
| .. versionchanged:: 1.17.0
| Casting between a simple data type and a structured one is possible only
| for "unsafe" casting. Casting to multiple fields is allowed, but
| casting from multiple fields is not.
|
| .. versionchanged:: 1.9.0
| Casting from numeric to string types in 'safe' casting mode requires
| that the string dtype length is long enough to store the max
| integer/float value converted.
|
| Raises
| ------
| ComplexWarning
| When casting from complex to float or int. To avoid this,
| one should use ``a.real.astype(t)``.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 2.5])
| >>> x
| array([1. , 2. , 2.5])
|
| >>> x.astype(int)
| array([1, 2, 2])
|
| byteswap(...)
| a.byteswap(inplace=False)
|
| Swap the bytes of the array elements
|
| Toggle between low-endian and big-endian data representation by
| returning a byteswapped array, optionally swapped in-place.
| Arrays of byte-strings are not swapped. The real and imaginary
| parts of a complex number are swapped individually.
|
| Parameters
| ----------
| inplace : bool, optional
| If ``True``, swap bytes in-place, default is ``False``.
|
| Returns
| -------
| out : ndarray
| The byteswapped array. If `inplace` is ``True``, this is
| a view to self.
|
| Examples
| --------
| >>> import numpy as np
| >>> A = np.array([1, 256, 8755], dtype=np.int16)
| >>> list(map(hex, A))
| ['0x1', '0x100', '0x2233']
| >>> A.byteswap(inplace=True)
| array([ 256, 1, 13090], dtype=int16)
| >>> list(map(hex, A))
| ['0x100', '0x1', '0x3322']
|
| Arrays of byte-strings are not swapped
|
| >>> A = np.array([b'ceg', b'fac'])
| >>> A.byteswap()
| array([b'ceg', b'fac'], dtype='|S3')
|
| ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| the same values but different representation in memory
|
| >>> A = np.array([1, 2, 3])
| >>> A.view(np.uint8)
| array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| 0, 0], dtype=uint8)
| >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| array([1, 2, 3])
| >>> A.view(np.uint8)
| array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| 0, 3], dtype=uint8)
|
| choose(...)
| a.choose(choices, out=None, mode='raise')
|
| Use an index array to construct a new array from a set of choices.
|
| Refer to `numpy.choose` for full documentation.
|
| See Also
| --------
| numpy.choose : equivalent function
|
| clip(...)
| a.clip(min=None, max=None, out=None, **kwargs)
|
| Return an array whose values are limited to ``[min, max]``.
| One of max or min must be given.
|
| Refer to `numpy.clip` for full documentation.
|
| See Also
| --------
| numpy.clip : equivalent function
|
| conj(...)
| a.conj()
|
| Complex-conjugate all elements.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| conjugate(...)
| a.conjugate()
|
| Return the complex conjugate, element-wise.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| dump(...)
| a.dump(file)
|
| Dump a pickle of the array to the specified file.
| The array can be read back with pickle.load or numpy.load.
|
| Parameters
| ----------
| file : str or Path
| A string naming the dump file.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| dumps(...)
| a.dumps()
|
| Returns the pickle of the array as a string.
| pickle.loads will convert the string back to an array.
|
| Parameters
| ----------
| None
|
| fill(...)
| a.fill(value)
|
| Fill the array with a scalar value.
|
| Parameters
| ----------
| value : scalar
| All elements of `a` will be assigned this value.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([1, 2])
| >>> a.fill(0)
| >>> a
| array([0, 0])
| >>> a = np.empty(2)
| >>> a.fill(1)
| >>> a
| array([1., 1.])
|
| Fill expects a scalar value and always behaves the same as assigning
| to a single array element. The following is a rare example where this
| distinction is important:
|
| >>> a = np.array([None, None], dtype=object)
| >>> a[0] = np.array(3)
| >>> a
| array([array(3), None], dtype=object)
| >>> a.fill(np.array(3))
| >>> a
| array([array(3), array(3)], dtype=object)
|
| Where other forms of assignments will unpack the array being assigned:
|
| >>> a[...] = np.array(3)
| >>> a
| array([3, 3], dtype=object)
|
| getfield(...)
| a.getfield(dtype, offset=0)
|
| Returns a field of the given array as a certain type.
|
| A field is a view of the array data with a given data-type. The values in
| the view are determined by the given type and the offset into the current
| array in bytes. The offset needs to be such that the view dtype fits in the
| array dtype; for example an array of dtype complex128 has 16-byte elements.
| If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| between 0 and 12 bytes.
|
| Parameters
| ----------
| dtype : str or dtype
| The data type of the view. The dtype size of the view can not be larger
| than that of the array itself.
| offset : int
| Number of bytes to skip before beginning the element view.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.diag([1.+1.j]*2)
| >>> x[1, 1] = 2 + 4.j
| >>> x
| array([[1.+1.j, 0.+0.j],
| [0.+0.j, 2.+4.j]])
| >>> x.getfield(np.float64)
| array([[1., 0.],
| [0., 2.]])
|
| By choosing an offset of 8 bytes we can select the complex part of the
| array for our view:
|
| >>> x.getfield(np.float64, offset=8)
| array([[1., 0.],
| [0., 4.]])
|
| item(...)
| a.item(*args)
|
| Copy an element of an array to a standard Python scalar and return it.
|
| Parameters
| ----------
| \*args : Arguments (variable number and type)
|
| * none: in this case, the method only works for arrays
| with one element (`a.size == 1`), which element is
| copied into a standard Python scalar object and returned.
|
| * int_type: this argument is interpreted as a flat index into
| the array, specifying which element to copy and return.
|
| * tuple of int_types: functions as does a single int_type argument,
| except that the argument is interpreted as an nd-index into the
| array.
|
| Returns
| -------
| z : Standard Python scalar object
| A copy of the specified element of the array as a suitable
| Python scalar
|
| Notes
| -----
| When the data type of `a` is longdouble or clongdouble, item() returns
| a scalar array object because there is no available Python scalar that
| would not lose information. Void arrays return a buffer object for item(),
| unless fields are defined, in which case a tuple is returned.
|
| `item` is very similar to a[args], except, instead of an array scalar,
| a standard Python scalar is returned. This can be useful for speeding up
| access to elements of the array and doing arithmetic on elements of the
| array using Python's optimized math.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.random.seed(123)
| >>> x = np.random.randint(9, size=(3, 3))
| >>> x
| array([[2, 2, 6],
| [1, 3, 6],
| [1, 0, 1]])
| >>> x.item(3)
| 1
| >>> x.item(7)
| 0
| >>> x.item((0, 1))
| 2
| >>> x.item((2, 2))
| 1
|
| For an array with object dtype, elements are returned as-is.
|
| >>> a = np.array([np.int64(1)], dtype=object)
| >>> a.item() #return np.int64
| np.int64(1)
|
| searchsorted(...)
| a.searchsorted(v, side='left', sorter=None)
|
| Find indices where elements of v should be inserted in a to maintain order.
|
| For full documentation, see `numpy.searchsorted`
|
| See Also
| --------
| numpy.searchsorted : equivalent function
|
| setfield(...)
| a.setfield(val, dtype, offset=0)
|
| Put a value into a specified place in a field defined by a data-type.
|
| Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| bytes into the field.
|
| Parameters
| ----------
| val : object
| Value to be placed in field.
| dtype : dtype object
| Data-type of the field in which to place `val`.
| offset : int, optional
| The number of bytes into the field at which to place `val`.
|
| Returns
| -------
| None
|
| See Also
| --------
| getfield
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.eye(3)
| >>> x.getfield(np.float64)
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
| >>> x.setfield(3, np.int32)
| >>> x.getfield(np.int32)
| array([[3, 3, 3],
| [3, 3, 3],
| [3, 3, 3]], dtype=int32)
| >>> x
| array([[1.0e+000, 1.5e-323, 1.5e-323],
| [1.5e-323, 1.0e+000, 1.5e-323],
| [1.5e-323, 1.5e-323, 1.0e+000]])
| >>> x.setfield(np.eye(3), np.int32)
| >>> x
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
|
| setflags(...)
| a.setflags(write=None, align=None, uic=None)
|
| Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| respectively.
|
| These Boolean-valued flags affect how numpy interprets the memory
| area used by `a` (see Notes below). The ALIGNED flag can only
| be set to True if the data is actually aligned according to the type.
| The WRITEBACKIFCOPY flag can never be set
| to True. The flag WRITEABLE can only be set to True if the array owns its
| own memory, or the ultimate owner of the memory exposes a writeable buffer
| interface, or is a string. (The exception for string is made so that
| unpickling can be done without copying memory.)
|
| Parameters
| ----------
| write : bool, optional
| Describes whether or not `a` can be written to.
| align : bool, optional
| Describes whether or not `a` is aligned properly for its type.
| uic : bool, optional
| Describes whether or not `a` is a copy of another "base" array.
|
| Notes
| -----
| Array flags provide information about how the memory area used
| for the array is to be interpreted. There are 7 Boolean flags
| in use, only three of which can be changed by the user:
| WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
|
| WRITEABLE (W) the data area can be written to;
|
| ALIGNED (A) the data and strides are aligned appropriately for the hardware
| (as determined by the compiler);
|
| WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| called, the base array will be updated with the contents of this array.
|
| All flags can be accessed using the single (upper case) letter as well
| as the full name.
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.array([[3, 1, 7],
| ... [2, 0, 0],
| ... [8, 5, 9]])
| >>> y
| array([[3, 1, 7],
| [2, 0, 0],
| [8, 5, 9]])
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
| >>> y.setflags(write=0, align=0)
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : False
| ALIGNED : False
| WRITEBACKIFCOPY : False
| >>> y.setflags(uic=1)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: cannot set WRITEBACKIFCOPY flag to True
|
| to_device(...)
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.ndarray:
|
| __class_getitem__(...)
| a.__class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.ndarray` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.ndarray` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.ndarray[Any, np.dtype[Any]]
| numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
| numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.ndarray:
|
| __array_interface__
| Array protocol: Python side.
|
| __array_struct__
| Array protocol: C-struct side.
|
| base
| Base object if memory is from some other object.
|
| Examples
| --------
| The base of an array that owns its memory is None:
|
| >>> import numpy as np
| >>> x = np.array([1,2,3,4])
| >>> x.base is None
| True
|
| Slicing creates a view, whose memory is shared with x:
|
| >>> y = x[2:]
| >>> y.base is x
| True
|
| ctypes
| An object to simplify the interaction of the array with the ctypes
| module.
|
| This attribute creates an object that makes it easier to use arrays
| when calling shared libraries with the ctypes module. The returned
| object has, among others, data, shape, and strides attributes (see
| Notes below) which themselves return ctypes objects that can be used
| as arguments to a shared library.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| c : Python object
| Possessing attributes data, shape, strides, etc.
|
| See Also
| --------
| numpy.ctypeslib
|
| Notes
| -----
| Below are the public attributes of this object which were documented
| in "Guide to NumPy" (we have omitted undocumented public attributes,
| as well as documented private attributes):
|
| .. autoattribute:: numpy._core._internal._ctypes.data
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.shape
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.strides
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.data_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.shape_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.strides_as
| :noindex:
|
| If the ctypes module is not available, then the ctypes attribute
| of array objects still returns something useful, but ctypes objects
| are not returned and errors may be raised instead. In particular,
| the object will still have the ``as_parameter`` attribute which will
| return an integer equal to the data attribute.
|
| Examples
| --------
| >>> import numpy as np
| >>> import ctypes
| >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| >>> x
| array([[0, 1],
| [2, 3]], dtype=int32)
| >>> x.ctypes.data
| 31962608 # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| c_uint(0)
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| c_ulong(4294967296)
| >>> x.ctypes.shape
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| >>> x.ctypes.strides
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
|
| device
|
| flags
| Information about the memory layout of the array.
|
| Attributes
| ----------
| C_CONTIGUOUS (C)
| The data is in a single, C-style contiguous segment.
| F_CONTIGUOUS (F)
| The data is in a single, Fortran-style contiguous segment.
| OWNDATA (O)
| The array owns the memory it uses or borrows it from another object.
| WRITEABLE (W)
| The data area can be written to. Setting this to False locks
| the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| from its base array at creation time, but a view of a writeable
| array may be subsequently locked while the base array remains writeable.
| (The opposite is not true, in that a view of a locked array may not
| be made writeable. However, currently, locking a base object does not
| lock any views that already reference it, so under that circumstance it
| is possible to alter the contents of a locked array via a previously
| created writeable view onto it.) Attempting to change a non-writeable
| array raises a RuntimeError exception.
| ALIGNED (A)
| The data and all elements are aligned appropriately for the hardware.
| WRITEBACKIFCOPY (X)
| This array is a copy of some other array. The C-API function
| PyArray_ResolveWritebackIfCopy must be called before deallocating
| to the base array will be updated with the contents of this array.
| FNC
| F_CONTIGUOUS and not C_CONTIGUOUS.
| FORC
| F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| BEHAVED (B)
| ALIGNED and WRITEABLE.
| CARRAY (CA)
| BEHAVED and C_CONTIGUOUS.
| FARRAY (FA)
| BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
|
| Notes
| -----
| The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| names are only supported in dictionary access.
|
| Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| changed by the user, via direct assignment to the attribute or dictionary
| entry, or by calling `ndarray.setflags`.
|
| The array flags cannot be set arbitrarily:
|
| - WRITEBACKIFCOPY can only be set ``False``.
| - ALIGNED can only be set ``True`` if the data is truly aligned.
| - WRITEABLE can only be set ``True`` if the array owns its own memory
| or the ultimate owner of the memory exposes a writeable buffer
| interface or is a string.
|
| Arrays can be both C-style and Fortran-style contiguous simultaneously.
| This is clear for 1-dimensional arrays, but can also be true for higher
| dimensional arrays.
|
| Even for contiguous arrays a stride for a given dimension
| ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| or the array has no elements.
| It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| Fortran-style contiguous arrays is true.
|
| itemset
|
| itemsize
| Length of one array element in bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1,2,3], dtype=np.float64)
| >>> x.itemsize
| 8
| >>> x = np.array([1,2,3], dtype=np.complex128)
| >>> x.itemsize
| 16
|
| nbytes
| Total bytes consumed by the elements of the array.
|
| Notes
| -----
| Does not include memory consumed by non-element attributes of the
| array object.
|
| See Also
| --------
| sys.getsizeof
| Memory consumed by the object itself without parents in case view.
| This does include memory consumed by non-element attributes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3,5,2), dtype=np.complex128)
| >>> x.nbytes
| 480
| >>> np.prod(x.shape) * x.itemsize
| 480
|
| ndim
| Number of array dimensions.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3])
| >>> x.ndim
| 1
| >>> y = np.zeros((2, 3, 4))
| >>> y.ndim
| 3
|
| newbyteorder
|
| size
| Number of elements in the array.
|
| Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| dimensions.
|
| Notes
| -----
| `a.size` returns a standard arbitrary precision Python integer. This
| may not be the case with other methods of obtaining the same value
| (like the suggested ``np.prod(a.shape)``, which returns an instance
| of ``np.int_``), and may be relevant if the value is used further in
| calculations that may overflow a fixed size integer type.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| >>> x.size
| 30
| >>> np.prod(x.shape)
| 30
|
| strides
| Tuple of bytes to step in each dimension when traversing an array.
|
| The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| is::
|
| offset = sum(np.array(i) * a.strides)
|
| A more detailed explanation of strides can be found in
| :ref:`arrays.ndarray`.
|
| .. warning::
|
| Setting ``arr.strides`` is discouraged and may be deprecated in the
| future. `numpy.lib.stride_tricks.as_strided` should be preferred
| to create a new view of the same data in a safer way.
|
| Notes
| -----
| Imagine an array of 32-bit integers (each 4 bytes)::
|
| x = np.array([[0, 1, 2, 3, 4],
| [5, 6, 7, 8, 9]], dtype=np.int32)
|
| This array is stored in memory as 40 bytes, one after the other
| (known as a contiguous block of memory). The strides of an array tell
| us how many bytes we have to skip in memory to move to the next position
| along a certain axis. For example, we have to skip 4 bytes (1 value) to
| move to the next column, but 20 bytes (5 values) to get to the same
| position in the next row. As such, the strides for the array `x` will be
| ``(20, 4)``.
|
| See Also
| --------
| numpy.lib.stride_tricks.as_strided
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| >>> y
| array([[[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]],
| [[12, 13, 14, 15],
| [16, 17, 18, 19],
| [20, 21, 22, 23]]])
| >>> y.strides
| (48, 16, 4)
| >>> y[1,1,1]
| 17
| >>> offset=sum(y.strides * np.array((1,1,1)))
| >>> offset/y.itemsize
| 17
|
| >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| >>> x.strides
| (32, 4, 224, 1344)
| >>> i = np.array([3,5,2,2])
| >>> offset = sum(i * x.strides)
| >>> x[3,5,2,2]
| 813
| >>> offset / x.itemsize
| 813
class mvoid(numpy.ma.MaskedArray)
| mvoid(data, mask=np.False_, dtype=None, fill_value=None, hardmask=False, copy=False, subok=True)
|
| Fake a 'void' object to use for masked array with structured dtypes.
|
| Method resolution order:
| mvoid
| numpy.ma.MaskedArray
| numpy.ndarray
| builtins.object
|
| Methods defined here:
|
| __getitem__(self, indx)
| Get the index.
|
| __iter__(self)
| Defines an iterator for mvoid
|
| __len__(self)
| Return len(self).
|
| __repr__ = __str__(self)
|
| __setitem__(self, indx, value)
| x.__setitem__(i, y) <==> x[i]=y
|
| Set item described by index. If value is masked, masks those
| locations.
|
| __str__(self)
| Return str(self).
|
| filled(self, fill_value=None)
| Return a copy with masked fields filled with a given value.
|
| Parameters
| ----------
| fill_value : array_like, optional
| The value to use for invalid entries. Can be scalar or
| non-scalar. If latter is the case, the filled array should
| be broadcastable over input array. Default is None, in
| which case the `fill_value` attribute is used instead.
|
| Returns
| -------
| filled_void
| A `np.void` object
|
| See Also
| --------
| MaskedArray.filled
|
| tolist(self)
| Transforms the mvoid object into a tuple.
|
| Masked fields are replaced by None.
|
| Returns
| -------
| returned_tuple
| Tuple of fields
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(self, data, mask=np.False_, dtype=None, fill_value=None, hardmask=False, copy=False, subok=True)
| Create a new masked array from scratch.
|
| Notes
| -----
| A masked array can also be created by taking a .view(MaskedArray).
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.ma.MaskedArray:
|
| __add__(self, other) from numpy.ma.core.MaskedArray
| Add self to other, and return a new masked array.
|
| __array_finalize__(self, obj) from numpy.ma.core.MaskedArray
| Finalizes the masked array.
|
| __array_wrap__(self, obj, context=None, return_scalar=False) from numpy.ma.core.MaskedArray
| Special hook for ufuncs.
|
| Wraps the numpy array and sets the mask according to context.
|
| __deepcopy__(self, memo=None) from numpy.ma.core.MaskedArray
| a.__deepcopy__(memo, /)
|
| Used if :func:`copy.deepcopy` is called on an array.
|
| __div__(self, other) from numpy.ma.core.MaskedArray
| Divide other into self, and return a new masked array.
|
| __eq__(self, other) from numpy.ma.core.MaskedArray
| Check whether other equals self elementwise.
|
| When either of the elements is masked, the result is masked as well,
| but the underlying boolean data are still set, with self and other
| considered equal if both are masked, and unequal otherwise.
|
| For structured arrays, all fields are combined, with masked values
| ignored. The result is masked if all fields were masked, with self
| and other considered equal only if both were fully masked.
|
| __float__(self) from numpy.ma.core.MaskedArray
| Convert to float.
|
| __floordiv__(self, other) from numpy.ma.core.MaskedArray
| Divide other into self, and return a new masked array.
|
| __ge__(self, other) from numpy.ma.core.MaskedArray
| Return self>=value.
|
| __getstate__(self) from numpy.ma.core.MaskedArray
| Return the internal state of the masked array, for pickling
| purposes.
|
| __gt__(self, other) from numpy.ma.core.MaskedArray
| Return self>value.
|
| __iadd__(self, other) from numpy.ma.core.MaskedArray
| Add other to self in-place.
|
| __idiv__(self, other) from numpy.ma.core.MaskedArray
| Divide self by other in-place.
|
| __ifloordiv__(self, other) from numpy.ma.core.MaskedArray
| Floor divide self by other in-place.
|
| __imul__(self, other) from numpy.ma.core.MaskedArray
| Multiply self by other in-place.
|
| __int__(self) from numpy.ma.core.MaskedArray
| Convert to int.
|
| __ipow__(self, other) from numpy.ma.core.MaskedArray
| Raise self to the power other, in place.
|
| __isub__(self, other) from numpy.ma.core.MaskedArray
| Subtract other from self in-place.
|
| __itruediv__(self, other) from numpy.ma.core.MaskedArray
| True divide self by other in-place.
|
| __le__(self, other) from numpy.ma.core.MaskedArray
| Return self<=value.
|
| __lt__(self, other) from numpy.ma.core.MaskedArray
| Return self<value.
|
| __mul__(self, other) from numpy.ma.core.MaskedArray
| Multiply self by other, and return a new masked array.
|
| __ne__(self, other) from numpy.ma.core.MaskedArray
| Check whether other does not equal self elementwise.
|
| When either of the elements is masked, the result is masked as well,
| but the underlying boolean data are still set, with self and other
| considered equal if both are masked, and unequal otherwise.
|
| For structured arrays, all fields are combined, with masked values
| ignored. The result is masked if all fields were masked, with self
| and other considered equal only if both were fully masked.
|
| __pow__(self, other) from numpy.ma.core.MaskedArray
| Raise self to the power other, masking the potential NaNs/Infs
|
| __radd__(self, other) from numpy.ma.core.MaskedArray
| Add other to self, and return a new masked array.
|
| __reduce__(self) from numpy.ma.core.MaskedArray
| Return a 3-tuple for pickling a MaskedArray.
|
| __rfloordiv__(self, other) from numpy.ma.core.MaskedArray
| Divide self into other, and return a new masked array.
|
| __rmul__(self, other) from numpy.ma.core.MaskedArray
| Multiply other by self, and return a new masked array.
|
| __rpow__(self, other) from numpy.ma.core.MaskedArray
| Raise other to the power self, masking the potential NaNs/Infs
|
| __rsub__(self, other) from numpy.ma.core.MaskedArray
| Subtract self from other, and return a new masked array.
|
| __rtruediv__(self, other) from numpy.ma.core.MaskedArray
| Divide self into other, and return a new masked array.
|
| __setmask__(self, mask, copy=False) from numpy.ma.core.MaskedArray
| Set the mask.
|
| __setstate__(self, state) from numpy.ma.core.MaskedArray
| Restore the internal state of the masked array, for
| pickling purposes. ``state`` is typically the output of the
| ``__getstate__`` output, and is a 5-tuple:
|
| - class name
| - a tuple giving the shape of the data
| - a typecode for the data
| - a binary string for the data
| - a binary string for the mask.
|
| __sub__(self, other) from numpy.ma.core.MaskedArray
| Subtract other from self, and return a new masked array.
|
| __truediv__(self, other) from numpy.ma.core.MaskedArray
| Divide other into self, and return a new masked array.
|
| all(self, axis=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns True if all elements evaluate to True.
|
| The output array is masked where all the values along the given axis
| are masked: if the output would have been a scalar and that all the
| values are masked, then the output is `masked`.
|
| Refer to `numpy.all` for full documentation.
|
| See Also
| --------
| numpy.ndarray.all : corresponding function for ndarrays
| numpy.all : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> np.ma.array([1,2,3]).all()
| True
| >>> a = np.ma.array([1,2,3], mask=True)
| >>> (a.all() is np.ma.masked)
| True
|
| anom(self, axis=None, dtype=None) from numpy.ma.core.MaskedArray
| Compute the anomalies (deviations from the arithmetic mean)
| along the given axis.
|
| Returns an array of anomalies, with the same shape as the input and
| where the arithmetic mean is computed along the given axis.
|
| Parameters
| ----------
| axis : int, optional
| Axis over which the anomalies are taken.
| The default is to use the mean of the flattened array as reference.
| dtype : dtype, optional
| Type to use in computing the variance. For arrays of integer type
| the default is float32; for arrays of float types it is the same as
| the array type.
|
| See Also
| --------
| mean : Compute the mean of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([1,2,3])
| >>> a.anom()
| masked_array(data=[-1., 0., 1.],
| mask=False,
| fill_value=1e+20)
|
| any(self, axis=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns True if any of the elements of `a` evaluate to True.
|
| Masked values are considered as False during computation.
|
| Refer to `numpy.any` for full documentation.
|
| See Also
| --------
| numpy.ndarray.any : corresponding function for ndarrays
| numpy.any : equivalent function
|
| argmax(self, axis=None, fill_value=None, out=None, *, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns array of indices of the maximum values along the given axis.
| Masked values are treated as if they had the value fill_value.
|
| Parameters
| ----------
| axis : {None, integer}
| If None, the index is into the flattened array, otherwise along
| the specified axis
| fill_value : scalar or None, optional
| Value used to fill in the masked values. If None, the output of
| maximum_fill_value(self._data) is used instead.
| out : {None, array}, optional
| Array into which the result can be placed. Its type is preserved
| and it must be of the right shape to hold the output.
|
| Returns
| -------
| index_array : {integer_array}
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.arange(6).reshape(2,3)
| >>> a.argmax()
| 5
| >>> a.argmax(0)
| array([1, 1, 1])
| >>> a.argmax(1)
| array([2, 2])
|
| argmin(self, axis=None, fill_value=None, out=None, *, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return array of indices to the minimum values along the given axis.
|
| Parameters
| ----------
| axis : {None, integer}
| If None, the index is into the flattened array, otherwise along
| the specified axis
| fill_value : scalar or None, optional
| Value used to fill in the masked values. If None, the output of
| minimum_fill_value(self._data) is used instead.
| out : {None, array}, optional
| Array into which the result can be placed. Its type is preserved
| and it must be of the right shape to hold the output.
|
| Returns
| -------
| ndarray or scalar
| If multi-dimension input, returns a new ndarray of indices to the
| minimum values along the given axis. Otherwise, returns a scalar
| of index to the minimum values along the given axis.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array(np.arange(4), mask=[1,1,0,0])
| >>> x.shape = (2,2)
| >>> x
| masked_array(
| data=[[--, --],
| [2, 3]],
| mask=[[ True, True],
| [False, False]],
| fill_value=999999)
| >>> x.argmin(axis=0, fill_value=-1)
| array([0, 0])
| >>> x.argmin(axis=0, fill_value=9)
| array([1, 1])
|
| argpartition(self, *args, **kwargs) from numpy.ma.core.MaskedArray
| a.argpartition(kth, axis=-1, kind='introselect', order=None)
|
| Returns the indices that would partition this array.
|
| Refer to `numpy.argpartition` for full documentation.
|
| .. versionadded:: 1.8.0
|
| See Also
| --------
| numpy.argpartition : equivalent function
|
| argsort(self, axis=<no value>, kind=None, order=None, endwith=True, fill_value=None, *, stable=False) from numpy.ma.core.MaskedArray
| Return an ndarray of indices that sort the array along the
| specified axis. Masked values are filled beforehand to
| `fill_value`.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which to sort. If None, the default, the flattened array
| is used.
|
| .. versionchanged:: 1.13.0
| Previously, the default was documented to be -1, but that was
| in error. At some future date, the default will change to -1, as
| originally intended.
| Until then, the axis should be given explicitly when
| ``arr.ndim > 1``, to avoid a FutureWarning.
| kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| The sorting algorithm used.
| order : list, optional
| When `a` is an array with fields defined, this argument specifies
| which fields to compare first, second, etc. Not all fields need be
| specified.
| endwith : {True, False}, optional
| Whether missing values (if any) should be treated as the largest values
| (True) or the smallest values (False)
| When the array contains unmasked values at the same extremes of the
| datatype, the ordering of these values and the masked values is
| undefined.
| fill_value : scalar or None, optional
| Value used internally for the masked values.
| If ``fill_value`` is not None, it supersedes ``endwith``.
| stable : bool, optional
| Only for compatibility with ``np.argsort``. Ignored.
|
| Returns
| -------
| index_array : ndarray, int
| Array of indices that sort `a` along the specified axis.
| In other words, ``a[index_array]`` yields a sorted `a`.
|
| See Also
| --------
| ma.MaskedArray.sort : Describes sorting algorithms used.
| lexsort : Indirect stable sort with multiple keys.
| numpy.ndarray.sort : Inplace sort.
|
| Notes
| -----
| See `sort` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([3,2,1], mask=[False, False, True])
| >>> a
| masked_array(data=[3, 2, --],
| mask=[False, False, True],
| fill_value=999999)
| >>> a.argsort()
| array([1, 0, 2])
|
| compress(self, condition, axis=None, out=None) from numpy.ma.core.MaskedArray
| Return `a` where condition is ``True``.
|
| If condition is a `~ma.MaskedArray`, missing values are considered
| as ``False``.
|
| Parameters
| ----------
| condition : var
| Boolean 1-d array selecting which entries to return. If len(condition)
| is less than the size of a along the axis, then output is truncated
| to length of condition array.
| axis : {None, int}, optional
| Axis along which the operation must be performed.
| out : {None, ndarray}, optional
| Alternative output array in which to place the result. It must have
| the same shape as the expected output but the type will be cast if
| necessary.
|
| Returns
| -------
| result : MaskedArray
| A :class:`~ma.MaskedArray` object.
|
| Notes
| -----
| Please note the difference with :meth:`compressed` !
| The output of :meth:`compress` has a mask, the output of
| :meth:`compressed` does not.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.compress([1, 0, 1])
| masked_array(data=[1, 3],
| mask=[False, False],
| fill_value=999999)
|
| >>> x.compress([1, 0, 1], axis=1)
| masked_array(
| data=[[1, 3],
| [--, --],
| [7, 9]],
| mask=[[False, False],
| [ True, True],
| [False, False]],
| fill_value=999999)
|
| compressed(self) from numpy.ma.core.MaskedArray
| Return all the non-masked data as a 1-D array.
|
| Returns
| -------
| data : ndarray
| A new `ndarray` holding the non-masked data is returned.
|
| Notes
| -----
| The result is **not** a MaskedArray!
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3)
| >>> x.compressed()
| array([0, 1])
| >>> type(x.compressed())
| <class 'numpy.ndarray'>
|
| N-D arrays are compressed to 1-D.
|
| >>> arr = [[1, 2], [3, 4]]
| >>> mask = [[1, 0], [0, 1]]
| >>> x = np.ma.array(arr, mask=mask)
| >>> x.compressed()
| array([2, 3])
|
| copy(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.copy(order='C')
|
| Return a copy of the array.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout of the copy. 'C' means C-order,
| 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| 'C' otherwise. 'K' means match the layout of `a` as closely
| as possible. (Note that this function and :func:`numpy.copy` are very
| similar but have different default values for their order=
| arguments, and this function always passes sub-classes through.)
|
| See also
| --------
| numpy.copy : Similar function with different default behavior
| numpy.copyto
|
| Notes
| -----
| This function is the preferred method for creating an array copy. The
| function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| and will not pass sub-classes through by default.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[1,2,3],[4,5,6]], order='F')
|
| >>> y = x.copy()
|
| >>> x.fill(0)
|
| >>> x
| array([[0, 0, 0],
| [0, 0, 0]])
|
| >>> y
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> y.flags['C_CONTIGUOUS']
| True
|
| For arrays containing Python objects (e.g. dtype=object),
| the copy is a shallow one. The new array will contain the
| same object which may lead to surprises if that object can
| be modified (is mutable):
|
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> b = a.copy()
| >>> b[2][0] = 10
| >>> a
| array([1, 'm', list([10, 3, 4])], dtype=object)
|
| To ensure all elements within an ``object`` array are copied,
| use `copy.deepcopy`:
|
| >>> import copy
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> c = copy.deepcopy(a)
| >>> c[2][0] = 10
| >>> c
| array([1, 'm', list([10, 3, 4])], dtype=object)
| >>> a
| array([1, 'm', list([2, 3, 4])], dtype=object)
|
| count(self, axis=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Count the non-masked elements of the array along the given axis.
|
| Parameters
| ----------
| axis : None or int or tuple of ints, optional
| Axis or axes along which the count is performed.
| The default, None, performs the count over all
| the dimensions of the input array. `axis` may be negative, in
| which case it counts from the last to the first axis.
|
| .. versionadded:: 1.10.0
|
| If this is a tuple of ints, the count is performed on multiple
| axes, instead of a single axis or all the axes as before.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| result : ndarray or scalar
| An array with the same shape as the input array, with the specified
| axis removed. If the array is a 0-d array, or if `axis` is None, a
| scalar is returned.
|
| See Also
| --------
| ma.count_masked : Count masked elements in array or along a given axis.
|
| Examples
| --------
| >>> import numpy.ma as ma
| >>> a = ma.arange(6).reshape((2, 3))
| >>> a[1, :] = ma.masked
| >>> a
| masked_array(
| data=[[0, 1, 2],
| [--, --, --]],
| mask=[[False, False, False],
| [ True, True, True]],
| fill_value=999999)
| >>> a.count()
| 3
|
| When the `axis` keyword is specified an array of appropriate size is
| returned.
|
| >>> a.count(axis=0)
| array([1, 1, 1])
| >>> a.count(axis=1)
| array([3, 0])
|
| cumprod(self, axis=None, dtype=None, out=None) from numpy.ma.core.MaskedArray
| Return the cumulative product of the array elements over the given axis.
|
| Masked values are set to 1 internally during the computation.
| However, their position is saved, and the result will be masked at
| the same locations.
|
| Refer to `numpy.cumprod` for full documentation.
|
| Notes
| -----
| The mask is lost if `out` is not a valid MaskedArray !
|
| Arithmetic is modular when using integer types, and no error is
| raised on overflow.
|
| See Also
| --------
| numpy.ndarray.cumprod : corresponding function for ndarrays
| numpy.cumprod : equivalent function
|
| cumsum(self, axis=None, dtype=None, out=None) from numpy.ma.core.MaskedArray
| Return the cumulative sum of the array elements over the given axis.
|
| Masked values are set to 0 internally during the computation.
| However, their position is saved, and the result will be masked at
| the same locations.
|
| Refer to `numpy.cumsum` for full documentation.
|
| Notes
| -----
| The mask is lost if `out` is not a valid :class:`ma.MaskedArray` !
|
| Arithmetic is modular when using integer types, and no error is
| raised on overflow.
|
| See Also
| --------
| numpy.ndarray.cumsum : corresponding function for ndarrays
| numpy.cumsum : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
| >>> marr.cumsum()
| masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33],
| mask=[False, False, False, True, True, True, False, False,
| False, False],
| fill_value=999999)
|
| diagonal(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.diagonal(offset=0, axis1=0, axis2=1)
|
| Return specified diagonals. In NumPy 1.9 the returned array is a
| read-only view instead of a copy as in previous NumPy versions. In
| a future version the read-only restriction will be removed.
|
| Refer to :func:`numpy.diagonal` for full documentation.
|
| See Also
| --------
| numpy.diagonal : equivalent function
|
| dot(self, b, out=None, strict=False) from numpy.ma.core.MaskedArray
| a.dot(b, out=None)
|
| Masked dot product of two arrays. Note that `out` and `strict` are
| located in different positions than in `ma.dot`. In order to
| maintain compatibility with the functional version, it is
| recommended that the optional arguments be treated as keyword only.
| At some point that may be mandatory.
|
| .. versionadded:: 1.10.0
|
| Parameters
| ----------
| b : masked_array_like
| Inputs array.
| out : masked_array, optional
| Output argument. This must have the exact kind that would be
| returned if it was not used. In particular, it must have the
| right type, must be C-contiguous, and its dtype must be the
| dtype that would be returned for `ma.dot(a,b)`. This is a
| performance feature. Therefore, if these conditions are not
| met, an exception is raised, instead of attempting to be
| flexible.
| strict : bool, optional
| Whether masked data are propagated (True) or set to 0 (False)
| for the computation. Default is False. Propagating the mask
| means that if a masked value appears in a row or column, the
| whole row or column is considered masked.
|
| .. versionadded:: 1.10.2
|
| See Also
| --------
| numpy.ma.dot : equivalent function
|
| flatten(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.flatten(order='C')
|
| Return a copy of the array collapsed into one dimension.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| 'C' means to flatten in row-major (C-style) order.
| 'F' means to flatten in column-major (Fortran-
| style) order. 'A' means to flatten in column-major
| order if `a` is Fortran *contiguous* in memory,
| row-major order otherwise. 'K' means to flatten
| `a` in the order the elements occur in memory.
| The default is 'C'.
|
| Returns
| -------
| y : ndarray
| A copy of the input array, flattened to one dimension.
|
| See Also
| --------
| ravel : Return a flattened array.
| flat : A 1-D flat iterator over the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,2], [3,4]])
| >>> a.flatten()
| array([1, 2, 3, 4])
| >>> a.flatten('F')
| array([1, 3, 2, 4])
|
| get_fill_value = fill_value(self) from numpy.ma.core.MaskedArray
| The filling value of the masked array is a scalar. When setting, None
| will set to a default based on the data type.
|
| Examples
| --------
| >>> import numpy as np
| >>> for dt in [np.int32, np.int64, np.float64, np.complex128]:
| ... np.ma.array([0, 1], dtype=dt).get_fill_value()
| ...
| np.int64(999999)
| np.int64(999999)
| np.float64(1e+20)
| np.complex128(1e+20+0j)
|
| >>> x = np.ma.array([0, 1.], fill_value=-np.inf)
| >>> x.fill_value
| np.float64(-inf)
| >>> x.fill_value = np.pi
| >>> x.fill_value
| np.float64(3.1415926535897931)
|
| Reset to default:
|
| >>> x.fill_value = None
| >>> x.fill_value
| np.float64(1e+20)
|
| get_imag = imag(self) from numpy.ma.core.MaskedArray
| The imaginary part of the masked array.
|
| This property is a view on the imaginary part of this `MaskedArray`.
|
| See Also
| --------
| real
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.imag
| masked_array(data=[1.0, --, 1.6],
| mask=[False, True, False],
| fill_value=1e+20)
|
| get_real = real(self) from numpy.ma.core.MaskedArray
| The real part of the masked array.
|
| This property is a view on the real part of this `MaskedArray`.
|
| See Also
| --------
| imag
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.real
| masked_array(data=[1.0, --, 3.45],
| mask=[False, True, False],
| fill_value=1e+20)
|
| harden_mask(self) from numpy.ma.core.MaskedArray
| Force the mask to hard, preventing unmasking by assignment.
|
| Whether the mask of a masked array is hard or soft is determined by
| its `~ma.MaskedArray.hardmask` property. `harden_mask` sets
| `~ma.MaskedArray.hardmask` to ``True`` (and returns the modified
| self).
|
| See Also
| --------
| ma.MaskedArray.hardmask
| ma.MaskedArray.soften_mask
|
| ids(self) from numpy.ma.core.MaskedArray
| Return the addresses of the data and mask areas.
|
| Parameters
| ----------
| None
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1])
| >>> x.ids()
| (166670640, 166659832) # may vary
|
| If the array has no mask, the address of `nomask` is returned. This address
| is typically not close to the data in memory:
|
| >>> x = np.ma.array([1, 2, 3])
| >>> x.ids()
| (166691080, 3083169284) # may vary
|
| iscontiguous(self) from numpy.ma.core.MaskedArray
| Return a boolean indicating whether the data is contiguous.
|
| Parameters
| ----------
| None
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1, 2, 3])
| >>> x.iscontiguous()
| True
|
| `iscontiguous` returns one of the flags of the masked array:
|
| >>> x.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : True
| OWNDATA : False
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
|
| max(self, axis=None, out=None, fill_value=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the maximum along a given axis.
|
| Parameters
| ----------
| axis : None or int or tuple of ints, optional
| Axis along which to operate. By default, ``axis`` is None and the
| flattened input is used.
| .. versionadded:: 1.7.0
| If this is a tuple of ints, the maximum is selected over multiple
| axes, instead of a single axis or all the axes as before.
| out : array_like, optional
| Alternative output array in which to place the result. Must
| be of the same shape and buffer length as the expected output.
| fill_value : scalar or None, optional
| Value used to fill in the masked values.
| If None, use the output of maximum_fill_value().
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| amax : array_like
| New array holding the result.
| If ``out`` was specified, ``out`` is returned.
|
| See Also
| --------
| ma.maximum_fill_value
| Returns the maximum filling value for a given datatype.
|
| Examples
| --------
| >>> import numpy.ma as ma
| >>> x = [[-1., 2.5], [4., -2.], [3., 0.]]
| >>> mask = [[0, 0], [1, 0], [1, 0]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> masked_x
| masked_array(
| data=[[-1.0, 2.5],
| [--, -2.0],
| [--, 0.0]],
| mask=[[False, False],
| [ True, False],
| [ True, False]],
| fill_value=1e+20)
| >>> ma.max(masked_x)
| 2.5
| >>> ma.max(masked_x, axis=0)
| masked_array(data=[-1.0, 2.5],
| mask=[False, False],
| fill_value=1e+20)
| >>> ma.max(masked_x, axis=1, keepdims=True)
| masked_array(
| data=[[2.5],
| [-2.0],
| [0.0]],
| mask=[[False],
| [False],
| [False]],
| fill_value=1e+20)
| >>> mask = [[1, 1], [1, 1], [1, 1]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> ma.max(masked_x, axis=1)
| masked_array(data=[--, --, --],
| mask=[ True, True, True],
| fill_value=1e+20,
| dtype=float64)
|
| mean(self, axis=None, dtype=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Returns the average of the array elements along given axis.
|
| Masked entries are ignored, and result elements which are not
| finite will be masked.
|
| Refer to `numpy.mean` for full documentation.
|
| See Also
| --------
| numpy.ndarray.mean : corresponding function for ndarrays
| numpy.mean : Equivalent function
| numpy.ma.average : Weighted average.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([1,2,3], mask=[False, False, True])
| >>> a
| masked_array(data=[1, 2, --],
| mask=[False, False, True],
| fill_value=999999)
| >>> a.mean()
| 1.5
|
| min(self, axis=None, out=None, fill_value=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the minimum along a given axis.
|
| Parameters
| ----------
| axis : None or int or tuple of ints, optional
| Axis along which to operate. By default, ``axis`` is None and the
| flattened input is used.
| .. versionadded:: 1.7.0
| If this is a tuple of ints, the minimum is selected over multiple
| axes, instead of a single axis or all the axes as before.
| out : array_like, optional
| Alternative output array in which to place the result. Must be of
| the same shape and buffer length as the expected output.
| fill_value : scalar or None, optional
| Value used to fill in the masked values.
| If None, use the output of `minimum_fill_value`.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| amin : array_like
| New array holding the result.
| If ``out`` was specified, ``out`` is returned.
|
| See Also
| --------
| ma.minimum_fill_value
| Returns the minimum filling value for a given datatype.
|
| Examples
| --------
| >>> import numpy.ma as ma
| >>> x = [[1., -2., 3.], [0.2, -0.7, 0.1]]
| >>> mask = [[1, 1, 0], [0, 0, 1]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> masked_x
| masked_array(
| data=[[--, --, 3.0],
| [0.2, -0.7, --]],
| mask=[[ True, True, False],
| [False, False, True]],
| fill_value=1e+20)
| >>> ma.min(masked_x)
| -0.7
| >>> ma.min(masked_x, axis=-1)
| masked_array(data=[3.0, -0.7],
| mask=[False, False],
| fill_value=1e+20)
| >>> ma.min(masked_x, axis=0, keepdims=True)
| masked_array(data=[[0.2, -0.7, 3.0]],
| mask=[[False, False, False]],
| fill_value=1e+20)
| >>> mask = [[1, 1, 1,], [1, 1, 1]]
| >>> masked_x = ma.masked_array(x, mask)
| >>> ma.min(masked_x, axis=0)
| masked_array(data=[--, --, --],
| mask=[ True, True, True],
| fill_value=1e+20,
| dtype=float64)
|
| nonzero(self) from numpy.ma.core.MaskedArray
| Return the indices of unmasked elements that are not zero.
|
| Returns a tuple of arrays, one for each dimension, containing the
| indices of the non-zero elements in that dimension. The corresponding
| non-zero values can be obtained with::
|
| a[a.nonzero()]
|
| To group the indices by element, rather than dimension, use
| instead::
|
| np.transpose(a.nonzero())
|
| The result of this is always a 2d array, with a row for each non-zero
| element.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| tuple_of_arrays : tuple
| Indices of elements that are non-zero.
|
| See Also
| --------
| numpy.nonzero :
| Function operating on ndarrays.
| flatnonzero :
| Return indices that are non-zero in the flattened version of the input
| array.
| numpy.ndarray.nonzero :
| Equivalent ndarray method.
| count_nonzero :
| Counts the number of non-zero elements in the input array.
|
| Examples
| --------
| >>> import numpy as np
| >>> import numpy.ma as ma
| >>> x = ma.array(np.eye(3))
| >>> x
| masked_array(
| data=[[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]],
| mask=False,
| fill_value=1e+20)
| >>> x.nonzero()
| (array([0, 1, 2]), array([0, 1, 2]))
|
| Masked elements are ignored.
|
| >>> x[1, 1] = ma.masked
| >>> x
| masked_array(
| data=[[1.0, 0.0, 0.0],
| [0.0, --, 0.0],
| [0.0, 0.0, 1.0]],
| mask=[[False, False, False],
| [False, True, False],
| [False, False, False]],
| fill_value=1e+20)
| >>> x.nonzero()
| (array([0, 2]), array([0, 2]))
|
| Indices can also be grouped by element.
|
| >>> np.transpose(x.nonzero())
| array([[0, 0],
| [2, 2]])
|
| 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, ma.nonzero(a > 3)
| yields the indices of the `a` where the condition is true.
|
| >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
| >>> a > 3
| masked_array(
| data=[[False, False, False],
| [ True, True, True],
| [ True, True, True]],
| mask=False,
| fill_value=True)
| >>> ma.nonzero(a > 3)
| (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
|
| The ``nonzero`` method of the condition array can also be called.
|
| >>> (a > 3).nonzero()
| (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
|
| partition(self, *args, **kwargs) from numpy.ma.core.MaskedArray
| a.partition(kth, axis=-1, kind='introselect', order=None)
|
| Partially sorts the elements in the array 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. In the output array, all elements smaller than the k-th element
| are located to the left of this element and all equal or greater are
| located to its right. The ordering of the elements in the two partitions
| on the either side of the k-th element in the output array is undefined.
|
| .. versionadded:: 1.8.0
|
| Parameters
| ----------
| kth : int or sequence of ints
| Element index to partition by. The kth element value 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 kth it will partition all elements
| indexed by kth of them into their sorted position at once.
|
| .. deprecated:: 1.22.0
| Passing booleans as index is deprecated.
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'introselect'}, optional
| Selection algorithm. Default is 'introselect'.
| order : str 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, and not all fields need to be specified,
| but unspecified fields will still be used, in the order in which
| they come up in the dtype, to break ties.
|
| See Also
| --------
| numpy.partition : Return a partitioned copy of an array.
| argpartition : Indirect partition.
| sort : Full sort.
|
| Notes
| -----
| See ``np.partition`` for notes on the different algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([3, 4, 2, 1])
| >>> a.partition(3)
| >>> a
| array([2, 1, 3, 4]) # may vary
|
| >>> a.partition((1, 3))
| >>> a
| array([1, 2, 3, 4])
|
| prod(self, axis=None, dtype=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the product of the array elements over the given axis.
|
| Masked elements are set to 1 internally for computation.
|
| Refer to `numpy.prod` for full documentation.
|
| Notes
| -----
| Arithmetic is modular when using integer types, and no error is raised
| on overflow.
|
| See Also
| --------
| numpy.ndarray.prod : corresponding function for ndarrays
| numpy.prod : equivalent function
|
| product = prod(self, axis=None, dtype=None, out=None, keepdims=<no value>)
|
| ptp(self, axis=None, out=None, fill_value=None, keepdims=False) from numpy.ma.core.MaskedArray
| Return (maximum - minimum) along the given dimension
| (i.e. peak-to-peak value).
|
| .. warning::
| `ptp` preserves the data type of the array. This means the
| return value for an input of signed integers with n bits
| (e.g. `np.int8`, `np.int16`, etc) is also a signed integer
| with n bits. In that case, peak-to-peak values greater than
| ``2**(n-1)-1`` will be returned as negative values. An example
| with a work-around is shown below.
|
| Parameters
| ----------
| axis : {None, int}, optional
| Axis along which to find the peaks. If None (default) the
| flattened array is used.
| out : {None, array_like}, optional
| Alternative output array in which to place the result. It must
| have the same shape and buffer length as the expected output
| but the type will be cast if necessary.
| fill_value : scalar or None, optional
| Value used to fill in the masked values.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the array.
|
| Returns
| -------
| ptp : ndarray.
| A new array holding the result, unless ``out`` was
| specified, in which case a reference to ``out`` is returned.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.MaskedArray([[4, 9, 2, 10],
| ... [6, 9, 7, 12]])
|
| >>> x.ptp(axis=1)
| masked_array(data=[8, 6],
| mask=False,
| fill_value=999999)
|
| >>> x.ptp(axis=0)
| masked_array(data=[2, 0, 5, 2],
| mask=False,
| fill_value=999999)
|
| >>> x.ptp()
| 10
|
| This example shows that a negative value can be returned when
| the input is an array of signed integers.
|
| >>> y = np.ma.MaskedArray([[1, 127],
| ... [0, 127],
| ... [-1, 127],
| ... [-2, 127]], dtype=np.int8)
| >>> y.ptp(axis=1)
| masked_array(data=[ 126, 127, -128, -127],
| mask=False,
| fill_value=np.int64(999999),
| dtype=int8)
|
| A work-around is to use the `view()` method to view the result as
| unsigned integers with the same bit width:
|
| >>> y.ptp(axis=1).view(np.uint8)
| masked_array(data=[126, 127, 128, 129],
| mask=False,
| fill_value=np.int64(999999),
| dtype=uint8)
|
| put(self, indices, values, mode='raise') from numpy.ma.core.MaskedArray
| Set storage-indexed locations to corresponding values.
|
| Sets self._data.flat[n] = values[n] for each n in indices.
| If `values` is shorter than `indices` then it will repeat.
| If `values` has some masked values, the initial mask is updated
| in consequence, else the corresponding values are unmasked.
|
| Parameters
| ----------
| indices : 1-D array_like
| Target indices, interpreted as integers.
| values : array_like
| Values to place in self._data copy at target indices.
| mode : {'raise', 'wrap', 'clip'}, optional
| Specifies how out-of-bounds indices will behave.
| 'raise' : raise an error.
| 'wrap' : wrap around.
| 'clip' : clip to the range.
|
| Notes
| -----
| `values` can be a scalar or length 1 array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.put([0,4,8],[10,20,30])
| >>> x
| masked_array(
| data=[[10, --, 3],
| [--, 20, --],
| [7, --, 30]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
|
| >>> x.put(4,999)
| >>> x
| masked_array(
| data=[[10, --, 3],
| [--, 999, --],
| [7, --, 30]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
|
| ravel(self, order='C') from numpy.ma.core.MaskedArray
| Returns a 1D version of self, as a view.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| The elements of `a` are read using this index order. 'C' means to
| index the elements in C-like order, with the last axis index
| changing fastest, back to the first axis index changing slowest.
| 'F' means to index the elements in Fortran-like index order, with
| the first index changing fastest, and the last index changing
| slowest. Note that the 'C' and 'F' options take no account of the
| memory layout of the underlying array, and only refer to the order
| of axis indexing. 'A' means to read the elements in Fortran-like
| index order if `m` is Fortran *contiguous* in memory, C-like order
| otherwise. 'K' means to read the elements in the order they occur
| in memory, except for reversing the data when strides are negative.
| By default, 'C' index order is used.
| (Masked arrays currently use 'A' on the data when 'K' is passed.)
|
| Returns
| -------
| MaskedArray
| Output view is of shape ``(self.size,)`` (or
| ``(np.ma.product(self.shape),)``).
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.ravel()
| masked_array(data=[1, --, 3, --, 5, --, 7, --, 9],
| mask=[False, True, False, True, False, True, False, True,
| False],
| fill_value=999999)
|
| repeat(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.repeat(repeats, axis=None)
|
| Repeat elements of an array.
|
| Refer to `numpy.repeat` for full documentation.
|
| See Also
| --------
| numpy.repeat : equivalent function
|
| reshape(self, *s, **kwargs) from numpy.ma.core.MaskedArray
| Give a new shape to the array without changing its data.
|
| Returns a masked array containing the same data, but with a new shape.
| The result is a view on the original array; if this is not possible, a
| ValueError is raised.
|
| Parameters
| ----------
| shape : int or tuple of ints
| The new shape should be compatible with the original shape. If an
| integer is supplied, then the result will be a 1-D array of that
| length.
| order : {'C', 'F'}, optional
| Determines whether the array data should be viewed as in C
| (row-major) or FORTRAN (column-major) order.
|
| Returns
| -------
| reshaped_array : array
| A new view on the array.
|
| See Also
| --------
| reshape : Equivalent function in the masked array module.
| numpy.ndarray.reshape : Equivalent method on ndarray object.
| numpy.reshape : Equivalent function in the NumPy module.
|
| Notes
| -----
| The reshaping operation cannot guarantee that a copy will not be made,
| to modify the shape in place, use ``a.shape = s``
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1])
| >>> x
| masked_array(
| data=[[--, 2],
| [3, --]],
| mask=[[ True, False],
| [False, True]],
| fill_value=999999)
| >>> x = x.reshape((4,1))
| >>> x
| masked_array(
| data=[[--],
| [2],
| [3],
| [--]],
| mask=[[ True],
| [False],
| [False],
| [ True]],
| fill_value=999999)
|
| resize(self, newshape, refcheck=True, order=False) from numpy.ma.core.MaskedArray
| .. warning::
|
| This method does nothing, except raise a ValueError exception. A
| masked array does not own its data and therefore cannot safely be
| resized in place. Use the `numpy.ma.resize` function instead.
|
| This method is difficult to implement safely and may be deprecated in
| future releases of NumPy.
|
| round(self, decimals=0, out=None) from numpy.ma.core.MaskedArray
| Return each element rounded to the given number of decimals.
|
| Refer to `numpy.around` for full documentation.
|
| See Also
| --------
| numpy.ndarray.round : corresponding function for ndarrays
| numpy.around : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> import numpy.ma as ma
| >>> x = ma.array([1.35, 2.5, 1.5, 1.75, 2.25, 2.75],
| ... mask=[0, 0, 0, 1, 0, 0])
| >>> ma.round(x)
| masked_array(data=[1.0, 2.0, 2.0, --, 2.0, 3.0],
| mask=[False, False, False, True, False, False],
| fill_value=1e+20)
|
| set_fill_value = fill_value(self, value=None) from numpy.ma.core.MaskedArray
|
| shrink_mask(self) from numpy.ma.core.MaskedArray
| Reduce a mask to nomask when possible.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| None
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4)
| >>> x.mask
| array([[False, False],
| [False, False]])
| >>> x.shrink_mask()
| masked_array(
| data=[[1, 2],
| [3, 4]],
| mask=False,
| fill_value=999999)
| >>> x.mask
| False
|
| soften_mask(self) from numpy.ma.core.MaskedArray
| Force the mask to soft (default), allowing unmasking by assignment.
|
| Whether the mask of a masked array is hard or soft is determined by
| its `~ma.MaskedArray.hardmask` property. `soften_mask` sets
| `~ma.MaskedArray.hardmask` to ``False`` (and returns the modified
| self).
|
| See Also
| --------
| ma.MaskedArray.hardmask
| ma.MaskedArray.harden_mask
|
| sort(self, axis=-1, kind=None, order=None, endwith=True, fill_value=None, *, stable=False) from numpy.ma.core.MaskedArray
| Sort the array, in-place
|
| Parameters
| ----------
| a : array_like
| Array to be sorted.
| axis : int, 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 : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| The sorting algorithm used.
| order : list, optional
| When `a` is a structured array, this argument specifies which fields
| to compare first, second, and so on. This list does not need to
| include all of the fields.
| endwith : {True, False}, optional
| Whether missing values (if any) should be treated as the largest values
| (True) or the smallest values (False)
| When the array contains unmasked values sorting at the same extremes of the
| datatype, the ordering of these values and the masked values is
| undefined.
| fill_value : scalar or None, optional
| Value used internally for the masked values.
| If ``fill_value`` is not None, it supersedes ``endwith``.
| stable : bool, optional
| Only for compatibility with ``np.sort``. Ignored.
|
| Returns
| -------
| sorted_array : ndarray
| Array of the same type and shape as `a`.
|
| See Also
| --------
| numpy.ndarray.sort : Method to sort an array in-place.
| argsort : Indirect sort.
| lexsort : Indirect stable sort on multiple keys.
| searchsorted : Find elements in a sorted array.
|
| Notes
| -----
| See ``sort`` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
| >>> # Default
| >>> a.sort()
| >>> a
| masked_array(data=[1, 3, 5, --, --],
| mask=[False, False, False, True, True],
| fill_value=999999)
|
| >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
| >>> # Put missing values in the front
| >>> a.sort(endwith=False)
| >>> a
| masked_array(data=[--, --, 1, 3, 5],
| mask=[ True, True, False, False, False],
| fill_value=999999)
|
| >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
| >>> # fill_value takes over endwith
| >>> a.sort(endwith=False, fill_value=3)
| >>> a
| masked_array(data=[1, --, --, 3, 5],
| mask=[False, True, True, False, False],
| fill_value=999999)
|
| squeeze(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.squeeze(axis=None)
|
| Remove axes of length one from `a`.
|
| Refer to `numpy.squeeze` for full documentation.
|
| See Also
| --------
| numpy.squeeze : equivalent function
|
| std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, mean=<no value>) from numpy.ma.core.MaskedArray
| Returns the standard deviation of the array elements along given axis.
|
| Masked entries are ignored.
|
| Refer to `numpy.std` for full documentation.
|
| See Also
| --------
| numpy.ndarray.std : corresponding function for ndarrays
| numpy.std : Equivalent function
|
| sum(self, axis=None, dtype=None, out=None, keepdims=<no value>) from numpy.ma.core.MaskedArray
| Return the sum of the array elements over the given axis.
|
| Masked elements are set to 0 internally.
|
| Refer to `numpy.sum` for full documentation.
|
| See Also
| --------
| numpy.ndarray.sum : corresponding function for ndarrays
| numpy.sum : equivalent function
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.sum()
| 25
| >>> x.sum(axis=1)
| masked_array(data=[4, 5, 16],
| mask=[False, False, False],
| fill_value=999999)
| >>> x.sum(axis=0)
| masked_array(data=[8, 5, 12],
| mask=[False, False, False],
| fill_value=999999)
| >>> print(type(x.sum(axis=0, dtype=np.int64)[0]))
| <class 'numpy.int64'>
|
| swapaxes(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.swapaxes(axis1, axis2)
|
| Return a view of the array with `axis1` and `axis2` interchanged.
|
| Refer to `numpy.swapaxes` for full documentation.
|
| See Also
| --------
| numpy.swapaxes : equivalent function
|
| take(self, indices, axis=None, out=None, mode='raise') from numpy.ma.core.MaskedArray
|
| tobytes(self, fill_value=None, order='C') from numpy.ma.core.MaskedArray
| Return the array data as a string containing the raw bytes in the array.
|
| The array is filled with a fill value before the string conversion.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| fill_value : scalar, optional
| Value used to fill in the masked values. Default is None, in which
| case `MaskedArray.fill_value` is used.
| order : {'C','F','A'}, optional
| Order of the data item in the copy. Default is 'C'.
|
| - 'C' -- C order (row major).
| - 'F' -- Fortran order (column major).
| - 'A' -- Any, current order of array.
| - None -- Same as 'A'.
|
| See Also
| --------
| numpy.ndarray.tobytes
| tolist, tofile
|
| Notes
| -----
| As for `ndarray.tobytes`, information about the shape, dtype, etc.,
| but also about `fill_value`, will be lost.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
| >>> x.tobytes()
| b'\x01\x00\x00\x00\x00\x00\x00\x00?B\x0f\x00\x00\x00\x00\x00?B\x0f\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00'
|
| tofile(self, fid, sep='', format='%s') from numpy.ma.core.MaskedArray
| Save a masked array to a file in binary format.
|
| .. warning::
| This function is not implemented yet.
|
| Raises
| ------
| NotImplementedError
| When `tofile` is called.
|
| toflex(self) from numpy.ma.core.MaskedArray
| Transforms a masked array into a flexible-type array.
|
| The flexible type array that is returned will have two fields:
|
| * the ``_data`` field stores the ``_data`` part of the array.
| * the ``_mask`` field stores the ``_mask`` part of the array.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| record : ndarray
| A new flexible-type `ndarray` with two fields: the first element
| containing a value, the second element containing the corresponding
| mask boolean. The returned record shape matches self.shape.
|
| Notes
| -----
| A side-effect of transforming a masked array into a flexible `ndarray` is
| that meta information (``fill_value``, ...) will be lost.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
| >>> x
| masked_array(
| data=[[1, --, 3],
| [--, 5, --],
| [7, --, 9]],
| mask=[[False, True, False],
| [ True, False, True],
| [False, True, False]],
| fill_value=999999)
| >>> x.toflex()
| array([[(1, False), (2, True), (3, False)],
| [(4, True), (5, False), (6, True)],
| [(7, False), (8, True), (9, False)]],
| dtype=[('_data', '<i8'), ('_mask', '?')])
|
| torecords = toflex(self)
|
| tostring(self, fill_value=None, order='C') from numpy.ma.core.MaskedArray
| A compatibility alias for `tobytes`, with exactly the same behavior.
|
| Despite its name, it returns `bytes` not `str`\ s.
|
| .. deprecated:: 1.19.0
|
| trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None) from numpy.ma.core.MaskedArray
| a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
|
| Return the sum along diagonals of the array.
|
| Refer to `numpy.trace` for full documentation.
|
| See Also
| --------
| numpy.trace : equivalent function
|
| transpose(self, *args, **params) from numpy.ma.core._arraymethod.<locals>
| a.transpose(*axes)
|
| Returns a view of the array with axes transposed.
|
| Refer to `numpy.transpose` for full documentation.
|
| Parameters
| ----------
| axes : None, tuple of ints, or `n` ints
|
| * None or no argument: reverses the order of the axes.
|
| * tuple of ints: `i` in the `j`-th place in the tuple means that the
| array's `i`-th axis becomes the transposed array's `j`-th axis.
|
| * `n` ints: same as an n-tuple of the same ints (this form is
| intended simply as a "convenience" alternative to the tuple form).
|
| Returns
| -------
| p : ndarray
| View of the array with its axes suitably permuted.
|
| See Also
| --------
| transpose : Equivalent function.
| ndarray.T : Array property returning the array transposed.
| ndarray.reshape : Give a new shape to an array without changing its data.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.transpose()
| array([[1, 3],
| [2, 4]])
| >>> a.transpose((1, 0))
| array([[1, 3],
| [2, 4]])
| >>> a.transpose(1, 0)
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.transpose()
| array([1, 2, 3, 4])
|
| unshare_mask(self) from numpy.ma.core.MaskedArray
| Copy the mask and set the `sharedmask` flag to ``False``.
|
| Whether the mask is shared between masked arrays can be seen from
| the `sharedmask` property. `unshare_mask` ensures the mask is not
| shared. A copy of the mask is only made if it was shared.
|
| See Also
| --------
| sharedmask
|
| var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, mean=<no value>) from numpy.ma.core.MaskedArray
| Compute the variance along the specified axis.
|
| 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.
|
| Parameters
| ----------
| a : array_like
| Array containing numbers whose variance is desired. If `a` is not an
| array, a conversion is attempted.
| axis : None or int or tuple of ints, optional
| Axis or axes along which the variance is computed. The default is to
| compute the variance of the flattened array.
|
| .. versionadded:: 1.7.0
|
| If this is a tuple of ints, a variance is performed over multiple axes,
| instead of a single axis or all the axes as before.
| dtype : data-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.
| out : ndarray, 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.
| ddof : {int, float}, optional
| "Delta Degrees of Freedom": the divisor used in the calculation is
| ``N - ddof``, where ``N`` represents the number of elements. By
| default `ddof` is zero. See notes for details about use of `ddof`.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the input array.
|
| If the default value is passed, then `keepdims` will not be
| passed through to the `var` method of sub-classes of
| `ndarray`, however any non-default value will be. If the
| sub-class' method does not implement `keepdims` any
| exceptions will be raised.
| where : array_like of bool, optional
| Elements to include in the variance. See `~numpy.ufunc.reduce` for
| details.
|
| .. versionadded:: 1.20.0
|
| mean : array like, optional
| Provide the mean to prevent its recalculation. The mean should have
| a shape as if it was calculated with ``keepdims=True``.
| The axis for the calculation of the mean should be the same as used in
| the call to this var function.
|
| .. versionadded:: 1.26.0
|
| correction : {int, float}, optional
| Array API compatible name for the ``ddof`` parameter. Only one of them
| can be provided at the same time.
|
| .. versionadded:: 2.0.0
|
| Returns
| -------
| variance : ndarray, see dtype parameter above
| If ``out=None``, returns a new array containing the variance;
| otherwise, a reference to the output array is returned.
|
| See Also
| --------
| std, mean, nanmean, nanstd, nanvar
| :ref:`ufuncs-output-type`
|
| Notes
| -----
| There are several common variants of the array variance calculation.
| Assuming the input `a` is a one-dimensional NumPy array and ``mean`` is
| either provided as an argument or computed as ``a.mean()``, NumPy
| computes the variance of an array as::
|
| N = len(a)
| d2 = abs(a - mean)**2 # abs is for complex `a`
| var = d2.sum() / (N - ddof) # note use of `ddof`
|
| Different values of the argument `ddof` are useful in different
| contexts. NumPy's default ``ddof=0`` corresponds with the expression:
|
| .. math::
|
| \frac{\sum_i{|a_i - \bar{a}|^2 }}{N}
|
| which is sometimes called the "population variance" in the field of
| statistics because it applies the definition of variance to `a` as if `a`
| were a complete population of possible observations.
|
| Many other libraries define the variance of an array differently, e.g.:
|
| .. math::
|
| \frac{\sum_i{|a_i - \bar{a}|^2}}{N - 1}
|
| In statistics, the resulting quantity is sometimed called the "sample
| variance" because if `a` is a random sample from a larger population,
| this calculation provides an unbiased estimate of the variance of the
| population. The use of :math:`N-1` in the denominator is often called
| "Bessel's correction" because it corrects for bias (toward lower values)
| in the variance estimate introduced when the sample mean of `a` is used
| in place of the true mean of the population. For this quantity, use
| ``ddof=1``.
|
| 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.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> np.var(a)
| 1.25
| >>> np.var(a, axis=0)
| array([1., 1.])
| >>> np.var(a, axis=1)
| array([0.25, 0.25])
|
| In single precision, var() can be inaccurate:
|
| >>> a = np.zeros((2, 512*512), dtype=np.float32)
| >>> a[0, :] = 1.0
| >>> a[1, :] = 0.1
| >>> np.var(a)
| 0.20250003
|
| Computing the variance in float64 is more accurate:
|
| >>> np.var(a, dtype=np.float64)
| 0.20249999932944759 # may vary
| >>> ((1-0.55)**2 + (0.1-0.55)**2)/2
| 0.2025
|
| Specifying a where argument:
|
| >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
| >>> np.var(a)
| 6.833333333333333 # may vary
| >>> np.var(a, where=[[True], [True], [False]])
| 4.0
|
| Using the mean keyword to save computation time:
|
| >>> import numpy as np
| >>> from timeit import timeit
| >>>
| >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
| >>> mean = np.mean(a, axis=1, keepdims=True)
| >>>
| >>> g = globals()
| >>> n = 10000
| >>> t1 = timeit("var = np.var(a, axis=1, mean=mean)", globals=g, number=n)
| >>> t2 = timeit("var = np.var(a, axis=1)", globals=g, number=n)
| >>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
| #doctest: +SKIP
| Percentage execution time saved 32%
|
| view(self, dtype=None, type=None, fill_value=None) from numpy.ma.core.MaskedArray
| Return a view of the MaskedArray data.
|
| Parameters
| ----------
| dtype : data-type or ndarray sub-class, optional
| Data-type descriptor of the returned view, e.g., float32 or int16.
| The default, None, results in the view having the same data-type
| as `a`. As with ``ndarray.view``, dtype can also be specified as
| an ndarray sub-class, which then specifies the type of the
| returned object (this is equivalent to setting the ``type``
| parameter).
| type : Python type, optional
| Type of the returned view, either ndarray or a subclass. The
| default None results in type preservation.
| fill_value : scalar, optional
| The value to use for invalid entries (None by default).
| If None, then this argument is inferred from the passed `dtype`, or
| in its absence the original array, as discussed in the notes below.
|
| See Also
| --------
| numpy.ndarray.view : Equivalent method on ndarray object.
|
| Notes
| -----
|
| ``a.view()`` is used two different ways:
|
| ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| of the array's memory with a different data-type. This can cause a
| reinterpretation of the bytes of memory.
|
| ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| returns an instance of `ndarray_subclass` that looks at the same array
| (same shape, dtype, etc.) This does not cause a reinterpretation of the
| memory.
|
| If `fill_value` is not specified, but `dtype` is specified (and is not
| an ndarray sub-class), the `fill_value` of the MaskedArray will be
| reset. If neither `fill_value` nor `dtype` are specified (or if
| `dtype` is an ndarray sub-class), then the fill value is preserved.
| Finally, if `fill_value` is specified, but `dtype` is not, the fill
| value is set to the specified value.
|
| For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| bytes per entry than the previous dtype (for example, converting a
| regular array to a structured array), then the behavior of the view
| cannot be predicted just from the superficial appearance of ``a`` (shown
| by ``print(a)``). It also depends on exactly how ``a`` is stored in
| memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus
| defined as a slice or transpose, etc., the view may give different
| results.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from numpy.ma.MaskedArray:
|
| T
|
| baseclass
| Class of the underlying data (read-only).
|
| data
| Returns the underlying data, as a view of the masked array.
|
| If the underlying data is a subclass of :class:`numpy.ndarray`, it is
| returned as such.
|
| >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
| >>> x.data
| matrix([[1, 2],
| [3, 4]])
|
| The type of the data can be accessed through the :attr:`baseclass`
| attribute.
|
| hardmask
| Specifies whether values can be unmasked through assignments.
|
| By default, assigning definite values to masked array entries will
| unmask them. When `hardmask` is ``True``, the mask will not change
| through assignments.
|
| See Also
| --------
| ma.MaskedArray.harden_mask
| ma.MaskedArray.soften_mask
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(10)
| >>> m = np.ma.masked_array(x, x>5)
| >>> assert not m.hardmask
|
| Since `m` has a soft mask, assigning an element value unmasks that
| element:
|
| >>> m[8] = 42
| >>> m
| masked_array(data=[0, 1, 2, 3, 4, 5, --, --, 42, --],
| mask=[False, False, False, False, False, False,
| True, True, False, True],
| fill_value=999999)
|
| After hardening, the mask is not affected by assignments:
|
| >>> hardened = np.ma.harden_mask(m)
| >>> assert m.hardmask and hardened is m
| >>> m[:] = 23
| >>> m
| masked_array(data=[23, 23, 23, 23, 23, 23, --, --, 23, --],
| mask=[False, False, False, False, False, False,
| True, True, False, True],
| fill_value=999999)
|
| imag
| The imaginary part of the masked array.
|
| This property is a view on the imaginary part of this `MaskedArray`.
|
| See Also
| --------
| real
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.imag
| masked_array(data=[1.0, --, 1.6],
| mask=[False, True, False],
| fill_value=1e+20)
|
| mT
| Return the matrix-transpose of the masked array.
|
| The matrix transpose is the transpose of the last two dimensions, even
| if the array is of higher dimension.
|
| .. versionadded:: 2.0
|
| Returns
| -------
| result: MaskedArray
| The masked array with the last two dimensions transposed
|
| Raises
| ------
| ValueError
| If the array is of dimension less than 2.
|
| See Also
| --------
| ndarray.mT:
| Equivalent method for arrays
|
| real
| The real part of the masked array.
|
| This property is a view on the real part of this `MaskedArray`.
|
| See Also
| --------
| imag
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
| >>> x.real
| masked_array(data=[1.0, --, 3.45],
| mask=[False, True, False],
| fill_value=1e+20)
|
| sharedmask
| Share status of the mask (read-only).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.ma.MaskedArray:
|
| __dict__
| dictionary for instance variables
|
| dtype
| Data-type of the array's elements.
|
| .. warning::
|
| Setting ``arr.dtype`` is discouraged and may be deprecated in the
| future. Setting will replace the ``dtype`` without modifying the
| memory (see also `ndarray.view` and `ndarray.astype`).
|
| Parameters
| ----------
| None
|
| Returns
| -------
| d : numpy dtype object
|
| See Also
| --------
| ndarray.astype : Cast the values contained in the array to a new data-type.
| ndarray.view : Create a view of the same data but a different data-type.
| numpy.dtype
|
| Examples
| --------
| >>> x
| array([[0, 1],
| [2, 3]])
| >>> x.dtype
| dtype('int32')
| >>> type(x.dtype)
| <type 'numpy.dtype'>
|
| fill_value
| The filling value of the masked array is a scalar. When setting, None
| will set to a default based on the data type.
|
| Examples
| --------
| >>> import numpy as np
| >>> for dt in [np.int32, np.int64, np.float64, np.complex128]:
| ... np.ma.array([0, 1], dtype=dt).get_fill_value()
| ...
| np.int64(999999)
| np.int64(999999)
| np.float64(1e+20)
| np.complex128(1e+20+0j)
|
| >>> x = np.ma.array([0, 1.], fill_value=-np.inf)
| >>> x.fill_value
| np.float64(-inf)
| >>> x.fill_value = np.pi
| >>> x.fill_value
| np.float64(3.1415926535897931)
|
| Reset to default:
|
| >>> x.fill_value = None
| >>> x.fill_value
| np.float64(1e+20)
|
| flat
| Return a flat iterator, or set a flattened version of self to value.
|
| mask
| Current mask.
|
| recordmask
| Get or set the mask of the array if it has no named fields. For
| structured arrays, returns a ndarray of booleans where entries are
| ``True`` if **all** the fields are masked, ``False`` otherwise:
|
| >>> x = np.ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
| ... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)],
| ... dtype=[('a', int), ('b', int)])
| >>> x.recordmask
| array([False, False, True, False, False])
|
| shape
| Tuple of array dimensions.
|
| The shape property is usually used to get the current shape of an array,
| but may also be used to reshape the array in-place by assigning a tuple of
| array dimensions to it. As with `numpy.reshape`, one of the new shape
| dimensions can be -1, in which case its value is inferred from the size of
| the array and the remaining dimensions. Reshaping an array in-place will
| fail if a copy is required.
|
| .. warning::
|
| Setting ``arr.shape`` is discouraged and may be deprecated in the
| future. Using `ndarray.reshape` is the preferred approach.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3, 4])
| >>> x.shape
| (4,)
| >>> y = np.zeros((2, 3, 4))
| >>> y.shape
| (2, 3, 4)
| >>> y.shape = (3, 8)
| >>> y
| array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| >>> y.shape = (3, 6)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: total size of new array must be unchanged
| >>> np.zeros((4,2))[::2].shape = (-1,)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| AttributeError: Incompatible shape for in-place modification. Use
| `.reshape()` to make a copy with the desired shape.
|
| See Also
| --------
| numpy.shape : Equivalent getter function.
| numpy.reshape : Function similar to setting ``shape``.
| ndarray.reshape : Method similar to setting ``shape``.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.ma.MaskedArray:
|
| __array_priority__ = 15
|
| __hash__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.ndarray:
|
| __abs__(self, /)
| abs(self)
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| a.__array__([dtype], *, copy=None)
|
| For ``dtype`` parameter it returns a new reference to self if
| ``dtype`` is not given or it matches array's data type.
| A new array of provided data type is returned if ``dtype``
| is different from the current data type of the array.
| For ``copy`` parameter it returns a new reference to self if
| ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| parameter. The method returns a new array for ``copy=True``, regardless of
| ``dtype`` parameter.
|
| A more detailed explanation of the ``__array__`` interface
| can be found in :ref:`dunder_array.interface`.
|
| __array_function__(...)
|
| __array_namespace__(...)
|
| __array_ufunc__(...)
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __complex__(...)
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __copy__(...)
| a.__copy__()
|
| Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
|
| Equivalent to ``a.copy(order='K')``.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __dlpack__(...)
| a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
|
| DLPack Protocol: Part of the Array API.
|
| __dlpack_device__(...)
| a.__dlpack_device__()
|
| DLPack Protocol: Part of the Array API.
|
| __format__(...)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __ilshift__(self, value, /)
| Return self<<=value.
|
| __imatmul__(self, value, /)
| Return self@=value.
|
| __imod__(self, value, /)
| Return self%=value.
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __invert__(self, /)
| ~self
|
| __ior__(self, value, /)
| Return self|=value.
|
| __irshift__(self, value, /)
| Return self>>=value.
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __matmul__(self, value, /)
| Return self@value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce_ex__(...)
| Helper for pickle.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmatmul__(self, value, /)
| Return value@self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __xor__(self, value, /)
| Return self^value.
|
| astype(...)
| a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
|
| Copy of the array, cast to a specified type.
|
| Parameters
| ----------
| dtype : str or dtype
| Typecode or data-type to which the array is cast.
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout order of the result.
| '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.
| Default is 'K'.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'unsafe'
| for backwards compatibility.
|
| * '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.
| subok : bool, optional
| If True, then sub-classes will be passed-through (default), otherwise
| the returned array will be forced to be a base-class array.
| copy : bool, optional
| By default, astype always returns a newly allocated array. If this
| is set to false, and the `dtype`, `order`, and `subok`
| requirements are satisfied, the input array is returned instead
| of a copy.
|
| Returns
| -------
| arr_t : ndarray
| Unless `copy` is False and the other conditions for returning the input
| array are satisfied (see description for `copy` input parameter), `arr_t`
| is a new array of the same shape as the input array, with dtype, order
| given by `dtype`, `order`.
|
| Notes
| -----
| .. versionchanged:: 1.17.0
| Casting between a simple data type and a structured one is possible only
| for "unsafe" casting. Casting to multiple fields is allowed, but
| casting from multiple fields is not.
|
| .. versionchanged:: 1.9.0
| Casting from numeric to string types in 'safe' casting mode requires
| that the string dtype length is long enough to store the max
| integer/float value converted.
|
| Raises
| ------
| ComplexWarning
| When casting from complex to float or int. To avoid this,
| one should use ``a.real.astype(t)``.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 2.5])
| >>> x
| array([1. , 2. , 2.5])
|
| >>> x.astype(int)
| array([1, 2, 2])
|
| byteswap(...)
| a.byteswap(inplace=False)
|
| Swap the bytes of the array elements
|
| Toggle between low-endian and big-endian data representation by
| returning a byteswapped array, optionally swapped in-place.
| Arrays of byte-strings are not swapped. The real and imaginary
| parts of a complex number are swapped individually.
|
| Parameters
| ----------
| inplace : bool, optional
| If ``True``, swap bytes in-place, default is ``False``.
|
| Returns
| -------
| out : ndarray
| The byteswapped array. If `inplace` is ``True``, this is
| a view to self.
|
| Examples
| --------
| >>> import numpy as np
| >>> A = np.array([1, 256, 8755], dtype=np.int16)
| >>> list(map(hex, A))
| ['0x1', '0x100', '0x2233']
| >>> A.byteswap(inplace=True)
| array([ 256, 1, 13090], dtype=int16)
| >>> list(map(hex, A))
| ['0x100', '0x1', '0x3322']
|
| Arrays of byte-strings are not swapped
|
| >>> A = np.array([b'ceg', b'fac'])
| >>> A.byteswap()
| array([b'ceg', b'fac'], dtype='|S3')
|
| ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| the same values but different representation in memory
|
| >>> A = np.array([1, 2, 3])
| >>> A.view(np.uint8)
| array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| 0, 0], dtype=uint8)
| >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| array([1, 2, 3])
| >>> A.view(np.uint8)
| array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| 0, 3], dtype=uint8)
|
| choose(...)
| a.choose(choices, out=None, mode='raise')
|
| Use an index array to construct a new array from a set of choices.
|
| Refer to `numpy.choose` for full documentation.
|
| See Also
| --------
| numpy.choose : equivalent function
|
| clip(...)
| a.clip(min=None, max=None, out=None, **kwargs)
|
| Return an array whose values are limited to ``[min, max]``.
| One of max or min must be given.
|
| Refer to `numpy.clip` for full documentation.
|
| See Also
| --------
| numpy.clip : equivalent function
|
| conj(...)
| a.conj()
|
| Complex-conjugate all elements.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| conjugate(...)
| a.conjugate()
|
| Return the complex conjugate, element-wise.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| dump(...)
| a.dump(file)
|
| Dump a pickle of the array to the specified file.
| The array can be read back with pickle.load or numpy.load.
|
| Parameters
| ----------
| file : str or Path
| A string naming the dump file.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| dumps(...)
| a.dumps()
|
| Returns the pickle of the array as a string.
| pickle.loads will convert the string back to an array.
|
| Parameters
| ----------
| None
|
| fill(...)
| a.fill(value)
|
| Fill the array with a scalar value.
|
| Parameters
| ----------
| value : scalar
| All elements of `a` will be assigned this value.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([1, 2])
| >>> a.fill(0)
| >>> a
| array([0, 0])
| >>> a = np.empty(2)
| >>> a.fill(1)
| >>> a
| array([1., 1.])
|
| Fill expects a scalar value and always behaves the same as assigning
| to a single array element. The following is a rare example where this
| distinction is important:
|
| >>> a = np.array([None, None], dtype=object)
| >>> a[0] = np.array(3)
| >>> a
| array([array(3), None], dtype=object)
| >>> a.fill(np.array(3))
| >>> a
| array([array(3), array(3)], dtype=object)
|
| Where other forms of assignments will unpack the array being assigned:
|
| >>> a[...] = np.array(3)
| >>> a
| array([3, 3], dtype=object)
|
| getfield(...)
| a.getfield(dtype, offset=0)
|
| Returns a field of the given array as a certain type.
|
| A field is a view of the array data with a given data-type. The values in
| the view are determined by the given type and the offset into the current
| array in bytes. The offset needs to be such that the view dtype fits in the
| array dtype; for example an array of dtype complex128 has 16-byte elements.
| If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| between 0 and 12 bytes.
|
| Parameters
| ----------
| dtype : str or dtype
| The data type of the view. The dtype size of the view can not be larger
| than that of the array itself.
| offset : int
| Number of bytes to skip before beginning the element view.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.diag([1.+1.j]*2)
| >>> x[1, 1] = 2 + 4.j
| >>> x
| array([[1.+1.j, 0.+0.j],
| [0.+0.j, 2.+4.j]])
| >>> x.getfield(np.float64)
| array([[1., 0.],
| [0., 2.]])
|
| By choosing an offset of 8 bytes we can select the complex part of the
| array for our view:
|
| >>> x.getfield(np.float64, offset=8)
| array([[1., 0.],
| [0., 4.]])
|
| item(...)
| a.item(*args)
|
| Copy an element of an array to a standard Python scalar and return it.
|
| Parameters
| ----------
| \*args : Arguments (variable number and type)
|
| * none: in this case, the method only works for arrays
| with one element (`a.size == 1`), which element is
| copied into a standard Python scalar object and returned.
|
| * int_type: this argument is interpreted as a flat index into
| the array, specifying which element to copy and return.
|
| * tuple of int_types: functions as does a single int_type argument,
| except that the argument is interpreted as an nd-index into the
| array.
|
| Returns
| -------
| z : Standard Python scalar object
| A copy of the specified element of the array as a suitable
| Python scalar
|
| Notes
| -----
| When the data type of `a` is longdouble or clongdouble, item() returns
| a scalar array object because there is no available Python scalar that
| would not lose information. Void arrays return a buffer object for item(),
| unless fields are defined, in which case a tuple is returned.
|
| `item` is very similar to a[args], except, instead of an array scalar,
| a standard Python scalar is returned. This can be useful for speeding up
| access to elements of the array and doing arithmetic on elements of the
| array using Python's optimized math.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.random.seed(123)
| >>> x = np.random.randint(9, size=(3, 3))
| >>> x
| array([[2, 2, 6],
| [1, 3, 6],
| [1, 0, 1]])
| >>> x.item(3)
| 1
| >>> x.item(7)
| 0
| >>> x.item((0, 1))
| 2
| >>> x.item((2, 2))
| 1
|
| For an array with object dtype, elements are returned as-is.
|
| >>> a = np.array([np.int64(1)], dtype=object)
| >>> a.item() #return np.int64
| np.int64(1)
|
| searchsorted(...)
| a.searchsorted(v, side='left', sorter=None)
|
| Find indices where elements of v should be inserted in a to maintain order.
|
| For full documentation, see `numpy.searchsorted`
|
| See Also
| --------
| numpy.searchsorted : equivalent function
|
| setfield(...)
| a.setfield(val, dtype, offset=0)
|
| Put a value into a specified place in a field defined by a data-type.
|
| Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| bytes into the field.
|
| Parameters
| ----------
| val : object
| Value to be placed in field.
| dtype : dtype object
| Data-type of the field in which to place `val`.
| offset : int, optional
| The number of bytes into the field at which to place `val`.
|
| Returns
| -------
| None
|
| See Also
| --------
| getfield
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.eye(3)
| >>> x.getfield(np.float64)
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
| >>> x.setfield(3, np.int32)
| >>> x.getfield(np.int32)
| array([[3, 3, 3],
| [3, 3, 3],
| [3, 3, 3]], dtype=int32)
| >>> x
| array([[1.0e+000, 1.5e-323, 1.5e-323],
| [1.5e-323, 1.0e+000, 1.5e-323],
| [1.5e-323, 1.5e-323, 1.0e+000]])
| >>> x.setfield(np.eye(3), np.int32)
| >>> x
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
|
| setflags(...)
| a.setflags(write=None, align=None, uic=None)
|
| Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| respectively.
|
| These Boolean-valued flags affect how numpy interprets the memory
| area used by `a` (see Notes below). The ALIGNED flag can only
| be set to True if the data is actually aligned according to the type.
| The WRITEBACKIFCOPY flag can never be set
| to True. The flag WRITEABLE can only be set to True if the array owns its
| own memory, or the ultimate owner of the memory exposes a writeable buffer
| interface, or is a string. (The exception for string is made so that
| unpickling can be done without copying memory.)
|
| Parameters
| ----------
| write : bool, optional
| Describes whether or not `a` can be written to.
| align : bool, optional
| Describes whether or not `a` is aligned properly for its type.
| uic : bool, optional
| Describes whether or not `a` is a copy of another "base" array.
|
| Notes
| -----
| Array flags provide information about how the memory area used
| for the array is to be interpreted. There are 7 Boolean flags
| in use, only three of which can be changed by the user:
| WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
|
| WRITEABLE (W) the data area can be written to;
|
| ALIGNED (A) the data and strides are aligned appropriately for the hardware
| (as determined by the compiler);
|
| WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| called, the base array will be updated with the contents of this array.
|
| All flags can be accessed using the single (upper case) letter as well
| as the full name.
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.array([[3, 1, 7],
| ... [2, 0, 0],
| ... [8, 5, 9]])
| >>> y
| array([[3, 1, 7],
| [2, 0, 0],
| [8, 5, 9]])
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
| >>> y.setflags(write=0, align=0)
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : False
| ALIGNED : False
| WRITEBACKIFCOPY : False
| >>> y.setflags(uic=1)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: cannot set WRITEBACKIFCOPY flag to True
|
| to_device(...)
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.ndarray:
|
| __class_getitem__(...)
| a.__class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.ndarray` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.ndarray` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.ndarray[Any, np.dtype[Any]]
| numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
| numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.ndarray:
|
| __array_interface__
| Array protocol: Python side.
|
| __array_struct__
| Array protocol: C-struct side.
|
| base
| Base object if memory is from some other object.
|
| Examples
| --------
| The base of an array that owns its memory is None:
|
| >>> import numpy as np
| >>> x = np.array([1,2,3,4])
| >>> x.base is None
| True
|
| Slicing creates a view, whose memory is shared with x:
|
| >>> y = x[2:]
| >>> y.base is x
| True
|
| ctypes
| An object to simplify the interaction of the array with the ctypes
| module.
|
| This attribute creates an object that makes it easier to use arrays
| when calling shared libraries with the ctypes module. The returned
| object has, among others, data, shape, and strides attributes (see
| Notes below) which themselves return ctypes objects that can be used
| as arguments to a shared library.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| c : Python object
| Possessing attributes data, shape, strides, etc.
|
| See Also
| --------
| numpy.ctypeslib
|
| Notes
| -----
| Below are the public attributes of this object which were documented
| in "Guide to NumPy" (we have omitted undocumented public attributes,
| as well as documented private attributes):
|
| .. autoattribute:: numpy._core._internal._ctypes.data
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.shape
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.strides
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.data_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.shape_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.strides_as
| :noindex:
|
| If the ctypes module is not available, then the ctypes attribute
| of array objects still returns something useful, but ctypes objects
| are not returned and errors may be raised instead. In particular,
| the object will still have the ``as_parameter`` attribute which will
| return an integer equal to the data attribute.
|
| Examples
| --------
| >>> import numpy as np
| >>> import ctypes
| >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| >>> x
| array([[0, 1],
| [2, 3]], dtype=int32)
| >>> x.ctypes.data
| 31962608 # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| c_uint(0)
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| c_ulong(4294967296)
| >>> x.ctypes.shape
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| >>> x.ctypes.strides
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
|
| device
|
| flags
| Information about the memory layout of the array.
|
| Attributes
| ----------
| C_CONTIGUOUS (C)
| The data is in a single, C-style contiguous segment.
| F_CONTIGUOUS (F)
| The data is in a single, Fortran-style contiguous segment.
| OWNDATA (O)
| The array owns the memory it uses or borrows it from another object.
| WRITEABLE (W)
| The data area can be written to. Setting this to False locks
| the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| from its base array at creation time, but a view of a writeable
| array may be subsequently locked while the base array remains writeable.
| (The opposite is not true, in that a view of a locked array may not
| be made writeable. However, currently, locking a base object does not
| lock any views that already reference it, so under that circumstance it
| is possible to alter the contents of a locked array via a previously
| created writeable view onto it.) Attempting to change a non-writeable
| array raises a RuntimeError exception.
| ALIGNED (A)
| The data and all elements are aligned appropriately for the hardware.
| WRITEBACKIFCOPY (X)
| This array is a copy of some other array. The C-API function
| PyArray_ResolveWritebackIfCopy must be called before deallocating
| to the base array will be updated with the contents of this array.
| FNC
| F_CONTIGUOUS and not C_CONTIGUOUS.
| FORC
| F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| BEHAVED (B)
| ALIGNED and WRITEABLE.
| CARRAY (CA)
| BEHAVED and C_CONTIGUOUS.
| FARRAY (FA)
| BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
|
| Notes
| -----
| The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| names are only supported in dictionary access.
|
| Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| changed by the user, via direct assignment to the attribute or dictionary
| entry, or by calling `ndarray.setflags`.
|
| The array flags cannot be set arbitrarily:
|
| - WRITEBACKIFCOPY can only be set ``False``.
| - ALIGNED can only be set ``True`` if the data is truly aligned.
| - WRITEABLE can only be set ``True`` if the array owns its own memory
| or the ultimate owner of the memory exposes a writeable buffer
| interface or is a string.
|
| Arrays can be both C-style and Fortran-style contiguous simultaneously.
| This is clear for 1-dimensional arrays, but can also be true for higher
| dimensional arrays.
|
| Even for contiguous arrays a stride for a given dimension
| ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| or the array has no elements.
| It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| Fortran-style contiguous arrays is true.
|
| itemset
|
| itemsize
| Length of one array element in bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1,2,3], dtype=np.float64)
| >>> x.itemsize
| 8
| >>> x = np.array([1,2,3], dtype=np.complex128)
| >>> x.itemsize
| 16
|
| nbytes
| Total bytes consumed by the elements of the array.
|
| Notes
| -----
| Does not include memory consumed by non-element attributes of the
| array object.
|
| See Also
| --------
| sys.getsizeof
| Memory consumed by the object itself without parents in case view.
| This does include memory consumed by non-element attributes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3,5,2), dtype=np.complex128)
| >>> x.nbytes
| 480
| >>> np.prod(x.shape) * x.itemsize
| 480
|
| ndim
| Number of array dimensions.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3])
| >>> x.ndim
| 1
| >>> y = np.zeros((2, 3, 4))
| >>> y.ndim
| 3
|
| newbyteorder
|
| size
| Number of elements in the array.
|
| Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| dimensions.
|
| Notes
| -----
| `a.size` returns a standard arbitrary precision Python integer. This
| may not be the case with other methods of obtaining the same value
| (like the suggested ``np.prod(a.shape)``, which returns an instance
| of ``np.int_``), and may be relevant if the value is used further in
| calculations that may overflow a fixed size integer type.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| >>> x.size
| 30
| >>> np.prod(x.shape)
| 30
|
| strides
| Tuple of bytes to step in each dimension when traversing an array.
|
| The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| is::
|
| offset = sum(np.array(i) * a.strides)
|
| A more detailed explanation of strides can be found in
| :ref:`arrays.ndarray`.
|
| .. warning::
|
| Setting ``arr.strides`` is discouraged and may be deprecated in the
| future. `numpy.lib.stride_tricks.as_strided` should be preferred
| to create a new view of the same data in a safer way.
|
| Notes
| -----
| Imagine an array of 32-bit integers (each 4 bytes)::
|
| x = np.array([[0, 1, 2, 3, 4],
| [5, 6, 7, 8, 9]], dtype=np.int32)
|
| This array is stored in memory as 40 bytes, one after the other
| (known as a contiguous block of memory). The strides of an array tell
| us how many bytes we have to skip in memory to move to the next position
| along a certain axis. For example, we have to skip 4 bytes (1 value) to
| move to the next column, but 20 bytes (5 values) to get to the same
| position in the next row. As such, the strides for the array `x` will be
| ``(20, 4)``.
|
| See Also
| --------
| numpy.lib.stride_tricks.as_strided
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| >>> y
| array([[[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]],
| [[12, 13, 14, 15],
| [16, 17, 18, 19],
| [20, 21, 22, 23]]])
| >>> y.strides
| (48, 16, 4)
| >>> y[1,1,1]
| 17
| >>> offset=sum(y.strides * np.array((1,1,1)))
| >>> offset/y.itemsize
| 17
|
| >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| >>> x.strides
| (32, 4, 224, 1344)
| >>> i = np.array([3,5,2,2])
| >>> offset = sum(i * x.strides)
| >>> x[3,5,2,2]
| 813
| >>> offset / x.itemsize
| 813
FUNCTIONS
allclose(a, b, masked_equal=True, rtol=1e-05, atol=1e-08)
Returns True if two arrays are element-wise equal within a tolerance.
This function is equivalent to `allclose` except that masked values
are treated as equal (default) or unequal, depending on the `masked_equal`
argument.
Parameters
----------
a, b : array_like
Input arrays to compare.
masked_equal : bool, optional
Whether masked values in `a` and `b` are considered equal (True) or not
(False). They are considered equal by default.
rtol : float, optional
Relative tolerance. The relative difference is equal to ``rtol * b``.
Default is 1e-5.
atol : float, optional
Absolute tolerance. The absolute difference is equal to `atol`.
Default is 1e-8.
Returns
-------
y : bool
Returns True if the two arrays are equal within the given
tolerance, False otherwise. If either array contains NaN, then
False is returned.
See Also
--------
all, any
numpy.allclose : the non-masked `allclose`.
Notes
-----
If the following equation is element-wise True, then `allclose` returns
True::
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
Return True if all elements of `a` and `b` are equal subject to
given tolerances.
Examples
--------
>>> import numpy as np
>>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
>>> a
masked_array(data=[10000000000.0, 1e-07, --],
mask=[False, False, True],
fill_value=1e+20)
>>> b = np.ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1])
>>> np.ma.allclose(a, b)
False
>>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
>>> b = np.ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1])
>>> np.ma.allclose(a, b)
True
>>> np.ma.allclose(a, b, masked_equal=False)
False
Masked values are not compared directly.
>>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
>>> b = np.ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1])
>>> np.ma.allclose(a, b)
True
>>> np.ma.allclose(a, b, masked_equal=False)
False
allequal(a, b, fill_value=True)
Return True if all entries of a and b are equal, using
fill_value as a truth value where either or both are masked.
Parameters
----------
a, b : array_like
Input arrays to compare.
fill_value : bool, optional
Whether masked values in a or b are considered equal (True) or not
(False).
Returns
-------
y : bool
Returns True if the two arrays are equal within the given
tolerance, False otherwise. If either array contains NaN,
then False is returned.
See Also
--------
all, any
numpy.ma.allclose
Examples
--------
>>> import numpy as np
>>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
>>> a
masked_array(data=[10000000000.0, 1e-07, --],
mask=[False, False, True],
fill_value=1e+20)
>>> b = np.array([1e10, 1e-7, -42.0])
>>> b
array([ 1.00000000e+10, 1.00000000e-07, -4.20000000e+01])
>>> np.ma.allequal(a, b, fill_value=False)
False
>>> np.ma.allequal(a, b)
True
alltrue = reduce(target, axis=0, dtype=None) method of numpy.ma.core._MaskedBinaryOperation instance
Reduce `target` along the given `axis`.
amax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the maximum of an array or maximum along an axis.
`amax` is an alias of `~numpy.max`.
See Also
--------
max : alias of this function
ndarray.max : equivalent method
amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the minimum of an array or minimum along an axis.
`amin` is an alias of `~numpy.min`.
See Also
--------
min : alias of this function
ndarray.min : equivalent method
append(a, b, axis=None)
Append values to the end of an array.
.. versionadded:: 1.9.0
Parameters
----------
a : array_like
Values are appended to a copy of this array.
b : array_like
These values are appended to a copy of `a`. It must be of the
correct shape (the same shape as `a`, excluding `axis`). If `axis`
is not specified, `b` can be any shape and will be flattened
before use.
axis : int, optional
The axis along which `v` are appended. If `axis` is not given,
both `a` and `b` are flattened before use.
Returns
-------
append : MaskedArray
A copy of `a` with `b` appended to `axis`. Note that `append`
does not occur in-place: a new array is allocated and filled. If
`axis` is None, the result is a flattened array.
See Also
--------
numpy.append : Equivalent function in the top-level NumPy module.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = ma.masked_values([1, 2, 3], 2)
>>> b = ma.masked_values([[4, 5, 6], [7, 8, 9]], 7)
>>> ma.append(a, b)
masked_array(data=[1, --, 3, 4, 5, 6, --, 8, 9],
mask=[False, True, False, False, False, False, True, False,
False],
fill_value=999999)
apply_along_axis(func1d, axis, arr, *args, **kwargs)
Apply a function to 1-D slices along the given axis.
Execute `func1d(a, *args, **kwargs)` where `func1d` operates on 1-D arrays
and `a` is a 1-D slice of `arr` along `axis`.
This is equivalent to (but faster than) the following use of `ndindex` and
`s_`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of indices::
Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
for kk in ndindex(Nk):
f = func1d(arr[ii + s_[:,] + kk])
Nj = f.shape
for jj in ndindex(Nj):
out[ii + jj + kk] = f[jj]
Equivalently, eliminating the inner loop, this can be expressed as::
Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
for kk in ndindex(Nk):
out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])
Parameters
----------
func1d : function (M,) -> (Nj...)
This function should accept 1-D arrays. It is applied to 1-D
slices of `arr` along the specified axis.
axis : integer
Axis along which `arr` is sliced.
arr : ndarray (Ni..., M, Nk...)
Input array.
args : any
Additional arguments to `func1d`.
kwargs : any
Additional named arguments to `func1d`.
.. versionadded:: 1.9.0
Returns
-------
out : ndarray (Ni..., Nj..., Nk...)
The output array. The shape of `out` is identical to the shape of
`arr`, except along the `axis` dimension. This axis is removed, and
replaced with new dimensions equal to the shape of the return value
of `func1d`. So if `func1d` returns a scalar `out` will have one
fewer dimensions than `arr`.
See Also
--------
apply_over_axes : Apply a function repeatedly over multiple axes.
Examples
--------
>>> import numpy as np
>>> def my_func(a):
... """Average first and last element of a 1-D array"""
... return (a[0] + a[-1]) * 0.5
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(my_func, 0, b)
array([4., 5., 6.])
>>> np.apply_along_axis(my_func, 1, b)
array([2., 5., 8.])
For a function that returns a 1D array, the number of dimensions in
`outarr` is the same as `arr`.
>>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
>>> np.apply_along_axis(sorted, 1, b)
array([[1, 7, 8],
[3, 4, 9],
[2, 5, 6]])
For a function that returns a higher dimensional array, those dimensions
are inserted in place of the `axis` dimension.
>>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> np.apply_along_axis(np.diag, -1, b)
array([[[1, 0, 0],
[0, 2, 0],
[0, 0, 3]],
[[4, 0, 0],
[0, 5, 0],
[0, 0, 6]],
[[7, 0, 0],
[0, 8, 0],
[0, 0, 9]]])
apply_over_axes(func, a, axes)
Apply a function repeatedly over multiple axes.
`func` is called as `res = func(a, axis)`, where `axis` is the first
element of `axes`. The result `res` of the function call must have
either the same dimensions as `a` or one less dimension. If `res`
has one less dimension than `a`, a dimension is inserted before
`axis`. The call to `func` is then repeated for each axis in `axes`,
with `res` as the first argument.
Parameters
----------
func : function
This function must take two arguments, `func(a, axis)`.
a : array_like
Input array.
axes : array_like
Axes over which `func` is applied; the elements must be integers.
Returns
-------
apply_over_axis : ndarray
The output array. The number of dimensions is the same as `a`,
but the shape can be different. This depends on whether `func`
changes the shape of its output with respect to its input.
See Also
--------
apply_along_axis :
Apply a function to 1-D slices of an array along the given axis.
Examples
--------
>>> import numpy as np
>>> a = np.ma.arange(24).reshape(2,3,4)
>>> a[:,0,1] = np.ma.masked
>>> a[:,1,:] = np.ma.masked
>>> a
masked_array(
data=[[[0, --, 2, 3],
[--, --, --, --],
[8, 9, 10, 11]],
[[12, --, 14, 15],
[--, --, --, --],
[20, 21, 22, 23]]],
mask=[[[False, True, False, False],
[ True, True, True, True],
[False, False, False, False]],
[[False, True, False, False],
[ True, True, True, True],
[False, False, False, False]]],
fill_value=999999)
>>> np.ma.apply_over_axes(np.ma.sum, a, [0,2])
masked_array(
data=[[[46],
[--],
[124]]],
mask=[[[False],
[ True],
[False]]],
fill_value=999999)
Tuple axis arguments to ufuncs are equivalent:
>>> np.ma.sum(a, axis=(0,2)).reshape((1,-1,1))
masked_array(
data=[[[46],
[--],
[124]]],
mask=[[[False],
[ True],
[False]]],
fill_value=999999)
argsort(a, axis=<no value>, kind=None, order=None, endwith=True, fill_value=None, *, stable=None)
Return an ndarray of indices that sort the array along the
specified axis. Masked values are filled beforehand to
`fill_value`.
Parameters
----------
axis : int, optional
Axis along which to sort. If None, the default, the flattened array
is used.
.. versionchanged:: 1.13.0
Previously, the default was documented to be -1, but that was
in error. At some future date, the default will change to -1, as
originally intended.
Until then, the axis should be given explicitly when
``arr.ndim > 1``, to avoid a FutureWarning.
kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
The sorting algorithm used.
order : list, optional
When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified.
endwith : {True, False}, optional
Whether missing values (if any) should be treated as the largest values
(True) or the smallest values (False)
When the array contains unmasked values at the same extremes of the
datatype, the ordering of these values and the masked values is
undefined.
fill_value : scalar or None, optional
Value used internally for the masked values.
If ``fill_value`` is not None, it supersedes ``endwith``.
stable : bool, optional
Only for compatibility with ``np.argsort``. Ignored.
Returns
-------
index_array : ndarray, int
Array of indices that sort `a` along the specified axis.
In other words, ``a[index_array]`` yields a sorted `a`.
See Also
--------
ma.MaskedArray.sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
numpy.ndarray.sort : Inplace sort.
Notes
-----
See `sort` for notes on the different sorting algorithms.
Examples
--------
>>> import numpy as np
>>> a = np.ma.array([3,2,1], mask=[False, False, True])
>>> a
masked_array(data=[3, 2, --],
mask=[False, False, True],
fill_value=999999)
>>> a.argsort()
array([1, 0, 2])
array(data, dtype=None, copy=False, order=None, mask=np.False_, fill_value=None, keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=0)
An array class with possibly masked values.
Masked values of True exclude the corresponding element from any
computation.
Construction::
x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True,
ndmin=0, fill_value=None, keep_mask=True, hard_mask=None,
shrink=True, order=None)
Parameters
----------
data : array_like
Input data.
mask : sequence, optional
Mask. Must be convertible to an array of booleans with the same
shape as `data`. True indicates a masked (i.e. invalid) data.
dtype : dtype, optional
Data type of the output.
If `dtype` is None, the type of the data argument (``data.dtype``)
is used. If `dtype` is not None and different from ``data.dtype``,
a copy is performed.
copy : bool, optional
Whether to copy the input data (True), or to use a reference instead.
Default is False.
subok : bool, optional
Whether to return a subclass of `MaskedArray` if possible (True) or a
plain `MaskedArray`. Default is True.
ndmin : int, optional
Minimum number of dimensions. Default is 0.
fill_value : scalar, optional
Value used to fill in the masked values when necessary.
If None, a default based on the data-type is used.
keep_mask : bool, optional
Whether to combine `mask` with the mask of the input data, if any
(True), or to use only `mask` for the output (False). Default is True.
hard_mask : bool, optional
Whether to use a hard mask or not. With a hard mask, masked values
cannot be unmasked. Default is False.
shrink : bool, optional
Whether to force compression of an empty mask. Default is True.
order : {'C', 'F', 'A'}, optional
Specify the order of the array. If order is 'C', then the array
will be in C-contiguous order (last-index varies the fastest).
If order is 'F', then the returned array will be in
Fortran-contiguous order (first-index varies the fastest).
If order is 'A' (default), then the returned array may be
in any order (either C-, Fortran-contiguous, or even discontiguous),
unless a copy is required, in which case it will be C-contiguous.
Examples
--------
>>> import numpy as np
The ``mask`` can be initialized with an array of boolean values
with the same shape as ``data``.
>>> data = np.arange(6).reshape((2, 3))
>>> np.ma.MaskedArray(data, mask=[[False, True, False],
... [False, False, True]])
masked_array(
data=[[0, --, 2],
[3, 4, --]],
mask=[[False, True, False],
[False, False, True]],
fill_value=999999)
Alternatively, the ``mask`` can be initialized to homogeneous boolean
array with the same shape as ``data`` by passing in a scalar
boolean value:
>>> np.ma.MaskedArray(data, mask=False)
masked_array(
data=[[0, 1, 2],
[3, 4, 5]],
mask=[[False, False, False],
[False, False, False]],
fill_value=999999)
>>> np.ma.MaskedArray(data, mask=True)
masked_array(
data=[[--, --, --],
[--, --, --]],
mask=[[ True, True, True],
[ True, True, True]],
fill_value=999999,
dtype=int64)
.. note::
The recommended practice for initializing ``mask`` with a scalar
boolean value is to use ``True``/``False`` rather than
``np.True_``/``np.False_``. The reason is :attr:`nomask`
is represented internally as ``np.False_``.
>>> np.False_ is np.ma.nomask
True
asanyarray(a, dtype=None)
Convert the input to a masked array, conserving subclasses.
If `a` is a subclass of `MaskedArray`, its class is conserved.
No copy is performed if the input is already an `ndarray`.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major ('C') or column-major ('FORTRAN') memory
representation. Default is 'C'.
Returns
-------
out : MaskedArray
MaskedArray interpretation of `a`.
See Also
--------
asarray : Similar to `asanyarray`, but does not conserve subclass.
Examples
--------
>>> import numpy as np
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]])
>>> np.ma.asanyarray(x)
masked_array(
data=[[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]],
mask=False,
fill_value=1e+20)
>>> type(np.ma.asanyarray(x))
<class 'numpy.ma.MaskedArray'>
asarray(a, dtype=None, order=None)
Convert the input to a masked array of the given data-type.
No copy is performed if the input is already an `ndarray`. If `a` is
a subclass of `MaskedArray`, a base class `MaskedArray` is returned.
Parameters
----------
a : array_like
Input data, in any form that can be converted to a masked array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists, ndarrays and masked arrays.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major ('C') or column-major ('FORTRAN') memory
representation. Default is 'C'.
Returns
-------
out : MaskedArray
Masked array interpretation of `a`.
See Also
--------
asanyarray : Similar to `asarray`, but conserves subclasses.
Examples
--------
>>> import numpy as np
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]])
>>> np.ma.asarray(x)
masked_array(
data=[[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.]],
mask=False,
fill_value=1e+20)
>>> type(np.ma.asarray(x))
<class 'numpy.ma.MaskedArray'>
average(a, axis=None, weights=None, returned=False, *, keepdims=<no value>)
Return the weighted average of array over the given axis.
Parameters
----------
a : array_like
Data to be averaged.
Masked entries are not taken into account in the computation.
axis : None or int or tuple of ints, optional
Axis or axes along which to average `a`. The default,
`axis=None`, will average over all of the elements of the input array.
If axis is a tuple of ints, averaging is performed on all of the axes
specified in the tuple instead of a single axis or all the axes as
before.
weights : array_like, optional
An array of weights associated with the values in `a`. Each value in
`a` contributes to the average according to its associated weight.
The array of weights must be the same shape as `a` if no axis is
specified, otherwise the weights must have dimensions and shape
consistent with `a` along the specified axis.
If `weights=None`, then all data in `a` are assumed to have a
weight equal to one.
The calculation is::
avg = sum(a * weights) / sum(weights)
where the sum is over all included elements.
The only constraint on the values of `weights` is that `sum(weights)`
must not be 0.
returned : bool, optional
Flag indicating whether a tuple ``(result, sum of weights)``
should be returned as output (True), or just the result (False).
Default is False.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
*Note:* `keepdims` will not work with instances of `numpy.matrix`
or other classes whose methods do not support `keepdims`.
.. versionadded:: 1.23.0
Returns
-------
average, [sum_of_weights] : (tuple of) scalar or MaskedArray
The average along the specified axis. When returned is `True`,
return a tuple with the average as the first element and the sum
of the weights as the second element. The return type is `np.float64`
if `a` is of integer type and floats smaller than `float64`, or the
input data-type, otherwise. If returned, `sum_of_weights` is always
`float64`.
Raises
------
ZeroDivisionError
When all weights along axis are zero. See `numpy.ma.average` for a
version robust to this type of error.
TypeError
When `weights` does not have the same shape as `a`, and `axis=None`.
ValueError
When `weights` does not have dimensions and shape consistent with `a`
along specified `axis`.
Examples
--------
>>> import numpy as np
>>> a = np.ma.array([1., 2., 3., 4.], mask=[False, False, True, True])
>>> np.ma.average(a, weights=[3, 1, 0, 0])
1.25
>>> x = np.ma.arange(6.).reshape(3, 2)
>>> x
masked_array(
data=[[0., 1.],
[2., 3.],
[4., 5.]],
mask=False,
fill_value=1e+20)
>>> data = np.arange(8).reshape((2, 2, 2))
>>> data
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.ma.average(data, axis=(0, 1), weights=[[1./4, 3./4], [1., 1./2]])
masked_array(data=[3.4, 4.4],
mask=[False, False],
fill_value=1e+20)
>>> np.ma.average(data, axis=0, weights=[[1./4, 3./4], [1., 1./2]])
Traceback (most recent call last):
...
ValueError: Shape of weights must be consistent
with shape of a along specified axis.
>>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3],
... returned=True)
>>> avg
masked_array(data=[2.6666666666666665, 3.6666666666666665],
mask=[False, False],
fill_value=1e+20)
With ``keepdims=True``, the following result has shape (3, 1).
>>> np.ma.average(x, axis=1, keepdims=True)
masked_array(
data=[[0.5],
[2.5],
[4.5]],
mask=False,
fill_value=1e+20)
choose(indices, choices, out=None, mode='raise')
Use an index array to construct a new array from a list of choices.
Given an array of integers and a list of n choice arrays, this method
will create a new array that merges each of the choice arrays. Where a
value in `index` is i, the new array will have the value that choices[i]
contains in the same place.
Parameters
----------
indices : ndarray of ints
This array must contain integers in ``[0, n-1]``, where n is the
number of choices.
choices : sequence of arrays
Choice arrays. The index array and all of the choices should be
broadcastable to the same shape.
out : array, optional
If provided, the result will be inserted into this array. It should
be of the appropriate shape and `dtype`.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
* 'raise' : raise an error
* 'wrap' : wrap around
* 'clip' : clip to the range
Returns
-------
merged_array : array
See Also
--------
choose : equivalent function
Examples
--------
>>> import numpy as np
>>> choice = np.array([[1,1,1], [2,2,2], [3,3,3]])
>>> a = np.array([2, 1, 0])
>>> np.ma.choose(a, choice)
masked_array(data=[3, 2, 1],
mask=False,
fill_value=999999)
clump_masked(a)
Returns a list of slices corresponding to the masked clumps of a 1-D array.
(A "clump" is defined as a contiguous region of the array).
Parameters
----------
a : ndarray
A one-dimensional masked array.
Returns
-------
slices : list of slice
The list of slices, one for each continuous region of masked elements
in `a`.
Notes
-----
.. versionadded:: 1.4.0
See Also
--------
flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges
notmasked_contiguous, clump_unmasked
Examples
--------
>>> import numpy as np
>>> a = np.ma.masked_array(np.arange(10))
>>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked
>>> np.ma.clump_masked(a)
[slice(0, 3, None), slice(6, 7, None), slice(8, 10, None)]
clump_unmasked(a)
Return list of slices corresponding to the unmasked clumps of a 1-D array.
(A "clump" is defined as a contiguous region of the array).
Parameters
----------
a : ndarray
A one-dimensional masked array.
Returns
-------
slices : list of slice
The list of slices, one for each continuous region of unmasked
elements in `a`.
Notes
-----
.. versionadded:: 1.4.0
See Also
--------
flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges
notmasked_contiguous, clump_masked
Examples
--------
>>> import numpy as np
>>> a = np.ma.masked_array(np.arange(10))
>>> a[[0, 1, 2, 6, 8, 9]] = np.ma.masked
>>> np.ma.clump_unmasked(a)
[slice(3, 6, None), slice(7, 8, None)]
common_fill_value(a, b)
Return the common filling value of two masked arrays, if any.
If ``a.fill_value == b.fill_value``, return the fill value,
otherwise return None.
Parameters
----------
a, b : MaskedArray
The masked arrays for which to compare fill values.
Returns
-------
fill_value : scalar or None
The common fill value, or None.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([0, 1.], fill_value=3)
>>> y = np.ma.array([0, 1.], fill_value=3)
>>> np.ma.common_fill_value(x, y)
3.0
compress_cols(a)
Suppress whole columns of a 2-D array that contain masked values.
This is equivalent to ``np.ma.compress_rowcols(a, 1)``, see
`compress_rowcols` for details.
Parameters
----------
x : array_like, MaskedArray
The array to operate on. If not a MaskedArray instance (or if no array
elements are masked), `x` is interpreted as a MaskedArray with
`mask` set to `nomask`. Must be a 2D array.
Returns
-------
compressed_array : ndarray
The compressed array.
See Also
--------
compress_rowcols
Examples
--------
>>> import numpy as np
>>> a = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
... [1, 0, 0],
... [0, 0, 0]])
>>> np.ma.compress_cols(a)
array([[1, 2],
[4, 5],
[7, 8]])
compress_nd(x, axis=None)
Suppress slices from multiple dimensions which contain masked values.
Parameters
----------
x : array_like, MaskedArray
The array to operate on. If not a MaskedArray instance (or if no array
elements are masked), `x` is interpreted as a MaskedArray with `mask`
set to `nomask`.
axis : tuple of ints or int, optional
Which dimensions to suppress slices from can be configured with this
parameter.
- If axis is a tuple of ints, those are the axes to suppress slices from.
- If axis is an int, then that is the only axis to suppress slices from.
- If axis is None, all axis are selected.
Returns
-------
compress_array : ndarray
The compressed array.
Examples
--------
>>> import numpy as np
>>> arr = [[1, 2], [3, 4]]
>>> mask = [[0, 1], [0, 0]]
>>> x = np.ma.array(arr, mask=mask)
>>> np.ma.compress_nd(x, axis=0)
array([[3, 4]])
>>> np.ma.compress_nd(x, axis=1)
array([[1],
[3]])
>>> np.ma.compress_nd(x)
array([[3]])
compress_rowcols(x, axis=None)
Suppress the rows and/or columns of a 2-D array that contain
masked values.
The suppression behavior is selected with the `axis` parameter.
- If axis is None, both rows and columns are suppressed.
- If axis is 0, only rows are suppressed.
- If axis is 1 or -1, only columns are suppressed.
Parameters
----------
x : array_like, MaskedArray
The array to operate on. If not a MaskedArray instance (or if no array
elements are masked), `x` is interpreted as a MaskedArray with
`mask` set to `nomask`. Must be a 2D array.
axis : int, optional
Axis along which to perform the operation. Default is None.
Returns
-------
compressed_array : ndarray
The compressed array.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
... [1, 0, 0],
... [0, 0, 0]])
>>> x
masked_array(
data=[[--, 1, 2],
[--, 4, 5],
[6, 7, 8]],
mask=[[ True, False, False],
[ True, False, False],
[False, False, False]],
fill_value=999999)
>>> np.ma.compress_rowcols(x)
array([[7, 8]])
>>> np.ma.compress_rowcols(x, 0)
array([[6, 7, 8]])
>>> np.ma.compress_rowcols(x, 1)
array([[1, 2],
[4, 5],
[7, 8]])
compress_rows(a)
Suppress whole rows of a 2-D array that contain masked values.
This is equivalent to ``np.ma.compress_rowcols(a, 0)``, see
`compress_rowcols` for details.
Parameters
----------
x : array_like, MaskedArray
The array to operate on. If not a MaskedArray instance (or if no array
elements are masked), `x` is interpreted as a MaskedArray with
`mask` set to `nomask`. Must be a 2D array.
Returns
-------
compressed_array : ndarray
The compressed array.
See Also
--------
compress_rowcols
Examples
--------
>>> import numpy as np
>>> a = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
... [1, 0, 0],
... [0, 0, 0]])
>>> np.ma.compress_rows(a)
array([[6, 7, 8]])
compressed(x)
Return all the non-masked data as a 1-D array.
This function is equivalent to calling the "compressed" method of a
`ma.MaskedArray`, see `ma.MaskedArray.compressed` for details.
See Also
--------
ma.MaskedArray.compressed : Equivalent method.
Examples
--------
>>> import numpy as np
Create an array with negative values masked:
>>> import numpy as np
>>> x = np.array([[1, -1, 0], [2, -1, 3], [7, 4, -1]])
>>> masked_x = np.ma.masked_array(x, mask=x < 0)
>>> masked_x
masked_array(
data=[[1, --, 0],
[2, --, 3],
[7, 4, --]],
mask=[[False, True, False],
[False, True, False],
[False, False, True]],
fill_value=999999)
Compress the masked array into a 1-D array of non-masked values:
>>> np.ma.compressed(masked_x)
array([1, 0, 2, 3, 7, 4])
concatenate(arrays, axis=0)
Concatenate a sequence of arrays along the given axis.
Parameters
----------
arrays : sequence of array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. Default is 0.
Returns
-------
result : MaskedArray
The concatenated array with any masked entries preserved.
See Also
--------
numpy.concatenate : Equivalent function in the top-level NumPy module.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = ma.arange(3)
>>> a[1] = ma.masked
>>> b = ma.arange(2, 5)
>>> a
masked_array(data=[0, --, 2],
mask=[False, True, False],
fill_value=999999)
>>> b
masked_array(data=[2, 3, 4],
mask=False,
fill_value=999999)
>>> ma.concatenate([a, b])
masked_array(data=[0, --, 2, 2, 3, 4],
mask=[False, True, False, False, False, False],
fill_value=999999)
convolve(a, v, mode='full', propagate_mask=True)
Returns the discrete, linear convolution of two one-dimensional sequences.
Parameters
----------
a, v : array_like
Input sequences.
mode : {'valid', 'same', 'full'}, optional
Refer to the `np.convolve` docstring.
propagate_mask : bool
If True, then if any masked element is included in the sum for a result
element, then the result is masked.
If False, then the result element is only masked if no non-masked cells
contribute towards it
Returns
-------
out : MaskedArray
Discrete, linear convolution of `a` and `v`.
See Also
--------
numpy.convolve : Equivalent function in the top-level NumPy module.
corrcoef(x, y=None, rowvar=True, bias=<no value>, allow_masked=True, ddof=<no value>)
Return Pearson product-moment correlation coefficients.
Except for the handling of missing data this function does the same as
`numpy.corrcoef`. For more details and examples, see `numpy.corrcoef`.
Parameters
----------
x : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `x` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same
shape as `x`.
rowvar : bool, optional
If `rowvar` is True (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : _NoValue, optional
Has no effect, do not use.
.. deprecated:: 1.10.0
allow_masked : bool, optional
If True, masked values are propagated pair-wise: if a value is masked
in `x`, the corresponding value is masked in `y`.
If False, raises an exception. Because `bias` is deprecated, this
argument needs to be treated as keyword only to avoid a warning.
ddof : _NoValue, optional
Has no effect, do not use.
.. deprecated:: 1.10.0
See Also
--------
numpy.corrcoef : Equivalent function in top-level NumPy module.
cov : Estimate the covariance matrix.
Notes
-----
This function accepts but discards arguments `bias` and `ddof`. This is
for backwards compatibility with previous versions of this function. These
arguments had no effect on the return values of the function and can be
safely ignored in this and previous versions of numpy.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([[0, 1], [1, 1]], mask=[0, 1, 0, 1])
>>> np.ma.corrcoef(x)
masked_array(
data=[[--, --],
[--, --]],
mask=[[ True, True],
[ True, True]],
fill_value=1e+20,
dtype=float64)
correlate(a, v, mode='valid', propagate_mask=True)
Cross-correlation of two 1-dimensional sequences.
Parameters
----------
a, v : array_like
Input sequences.
mode : {'valid', 'same', 'full'}, optional
Refer to the `np.convolve` docstring. Note that the default
is 'valid', unlike `convolve`, which uses 'full'.
propagate_mask : bool
If True, then a result element is masked if any masked element contributes towards it.
If False, then a result element is only masked if no non-masked element
contribute towards it
Returns
-------
out : MaskedArray
Discrete cross-correlation of `a` and `v`.
See Also
--------
numpy.correlate : Equivalent function in the top-level NumPy module.
Examples
--------
Basic correlation:
>>> a = np.ma.array([1, 2, 3])
>>> v = np.ma.array([0, 1, 0])
>>> np.ma.correlate(a, v, mode='valid')
masked_array(data=[2],
mask=[False],
fill_value=999999)
Correlation with masked elements:
>>> a = np.ma.array([1, 2, 3], mask=[False, True, False])
>>> v = np.ma.array([0, 1, 0])
>>> np.ma.correlate(a, v, mode='valid', propagate_mask=True)
masked_array(data=[--],
mask=[ True],
fill_value=999999,
dtype=int64)
Correlation with different modes and mixed array types:
>>> a = np.ma.array([1, 2, 3])
>>> v = np.ma.array([0, 1, 0])
>>> np.ma.correlate(a, v, mode='full')
masked_array(data=[0, 1, 2, 3, 0],
mask=[False, False, False, False, False],
fill_value=999999)
count_masked(arr, axis=None)
Count the number of masked elements along the given axis.
Parameters
----------
arr : array_like
An array with (possibly) masked elements.
axis : int, optional
Axis along which to count. If None (default), a flattened
version of the array is used.
Returns
-------
count : int, ndarray
The total number of masked elements (axis=None) or the number
of masked elements along each slice of the given axis.
See Also
--------
MaskedArray.count : Count non-masked elements.
Examples
--------
>>> import numpy as np
>>> a = np.arange(9).reshape((3,3))
>>> a = np.ma.array(a)
>>> a[1, 0] = np.ma.masked
>>> a[1, 2] = np.ma.masked
>>> a[2, 1] = np.ma.masked
>>> a
masked_array(
data=[[0, 1, 2],
[--, 4, --],
[6, --, 8]],
mask=[[False, False, False],
[ True, False, True],
[False, True, False]],
fill_value=999999)
>>> np.ma.count_masked(a)
3
When the `axis` keyword is used an array is returned.
>>> np.ma.count_masked(a, axis=0)
array([1, 1, 1])
>>> np.ma.count_masked(a, axis=1)
array([0, 2, 1])
cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None)
Estimate the covariance matrix.
Except for the handling of missing data this function does the same as
`numpy.cov`. For more details and examples, see `numpy.cov`.
By default, masked values are recognized as such. If `x` and `y` have the
same shape, a common mask is allocated: if ``x[i,j]`` is masked, then
``y[i,j]`` will also be masked.
Setting `allow_masked` to False will raise an exception if values are
missing in either of the input arrays.
Parameters
----------
x : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `x` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same
shape as `x`.
rowvar : bool, optional
If `rowvar` is True (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : bool, optional
Default normalization (False) is by ``(N-1)``, where ``N`` is the
number of observations given (unbiased estimate). If `bias` is True,
then normalization is by ``N``. This keyword can be overridden by
the keyword ``ddof`` in numpy versions >= 1.5.
allow_masked : bool, optional
If True, masked values are propagated pair-wise: if a value is masked
in `x`, the corresponding value is masked in `y`.
If False, raises a `ValueError` exception when some values are missing.
ddof : {None, int}, optional
If not ``None`` normalization is by ``(N - ddof)``, where ``N`` is
the number of observations; this overrides the value implied by
``bias``. The default value is ``None``.
.. versionadded:: 1.5
Raises
------
ValueError
Raised if some values are missing and `allow_masked` is False.
See Also
--------
numpy.cov
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([[0, 1], [1, 1]], mask=[0, 1, 0, 1])
>>> y = np.ma.array([[1, 0], [0, 1]], mask=[0, 0, 1, 1])
>>> np.ma.cov(x, y)
masked_array(
data=[[--, --, --, --],
[--, --, --, --],
[--, --, --, --],
[--, --, --, --]],
mask=[[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True]],
fill_value=1e+20,
dtype=float64)
default_fill_value(obj)
Return the default fill value for the argument object.
The default filling value depends on the datatype of the input
array or the type of the input scalar:
======== ========
datatype default
======== ========
bool True
int 999999
float 1.e20
complex 1.e20+0j
object '?'
string 'N/A'
======== ========
For structured types, a structured scalar is returned, with each field the
default fill value for its type.
For subarray types, the fill value is an array of the same size containing
the default scalar fill value.
Parameters
----------
obj : ndarray, dtype or scalar
The array data-type or scalar for which the default fill value
is returned.
Returns
-------
fill_value : scalar
The default fill value.
Examples
--------
>>> import numpy as np
>>> np.ma.default_fill_value(1)
999999
>>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
1e+20
>>> np.ma.default_fill_value(np.dtype(complex))
(1e+20+0j)
diag(v, k=0)
Extract a diagonal or construct a diagonal array.
This function is the equivalent of `numpy.diag` that takes masked
values into account, see `numpy.diag` for details.
See Also
--------
numpy.diag : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
Create an array with negative values masked:
>>> import numpy as np
>>> x = np.array([[11.2, -3.973, 18], [0.801, -1.41, 12], [7, 33, -12]])
>>> masked_x = np.ma.masked_array(x, mask=x < 0)
>>> masked_x
masked_array(
data=[[11.2, --, 18.0],
[0.801, --, 12.0],
[7.0, 33.0, --]],
mask=[[False, True, False],
[False, True, False],
[False, False, True]],
fill_value=1e+20)
Isolate the main diagonal from the masked array:
>>> np.ma.diag(masked_x)
masked_array(data=[11.2, --, --],
mask=[False, True, True],
fill_value=1e+20)
Isolate the first diagonal below the main diagonal:
>>> np.ma.diag(masked_x, -1)
masked_array(data=[0.801, 33.0],
mask=[False, False],
fill_value=1e+20)
diff(a, /, n=1, axis=-1, prepend=<no value>, append=<no value>)
Calculate the n-th discrete difference along the given axis.
The first difference is given by ``out[i] = a[i+1] - a[i]`` along
the given axis, higher differences are calculated by using `diff`
recursively.
Preserves the input mask.
Parameters
----------
a : array_like
Input array
n : int, optional
The number of times values are differenced. If zero, the input
is returned as-is.
axis : int, optional
The axis along which the difference is taken, default is the
last axis.
prepend, append : array_like, optional
Values to prepend or append to `a` along axis prior to
performing the difference. Scalar values are expanded to
arrays with length 1 in the direction of axis and the shape
of the input array in along all other axes. Otherwise the
dimension and shape must match `a` except along axis.
Returns
-------
diff : MaskedArray
The n-th differences. The shape of the output is the same as `a`
except along `axis` where the dimension is smaller by `n`. The
type of the output is the same as the type of the difference
between any two elements of `a`. This is the same as the type of
`a` in most cases. A notable exception is `datetime64`, which
results in a `timedelta64` output array.
See Also
--------
numpy.diff : Equivalent function in the top-level NumPy module.
Notes
-----
Type is preserved for boolean arrays, so the result will contain
`False` when consecutive elements are the same and `True` when they
differ.
For unsigned integer arrays, the results will also be unsigned. This
should not be surprising, as the result is consistent with
calculating the difference directly:
>>> u8_arr = np.array([1, 0], dtype=np.uint8)
>>> np.ma.diff(u8_arr)
masked_array(data=[255],
mask=False,
fill_value=np.int64(999999),
dtype=uint8)
>>> u8_arr[1,...] - u8_arr[0,...]
255
If this is not desirable, then the array should be cast to a larger
integer type first:
>>> i16_arr = u8_arr.astype(np.int16)
>>> np.ma.diff(i16_arr)
masked_array(data=[-1],
mask=False,
fill_value=np.int64(999999),
dtype=int16)
Examples
--------
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 7, 0, 2, 3])
>>> x = np.ma.masked_where(a < 2, a)
>>> np.ma.diff(x)
masked_array(data=[--, 1, 1, 3, --, --, 1],
mask=[ True, False, False, False, True, True, False],
fill_value=999999)
>>> np.ma.diff(x, n=2)
masked_array(data=[--, 0, 2, --, --, --],
mask=[ True, False, False, True, True, True],
fill_value=999999)
>>> a = np.array([[1, 3, 1, 5, 10], [0, 1, 5, 6, 8]])
>>> x = np.ma.masked_equal(a, value=1)
>>> np.ma.diff(x)
masked_array(
data=[[--, --, --, 5],
[--, --, 1, 2]],
mask=[[ True, True, True, False],
[ True, True, False, False]],
fill_value=1)
>>> np.ma.diff(x, axis=0)
masked_array(data=[[--, --, --, 1, -2]],
mask=[[ True, True, True, False, False]],
fill_value=1)
dot(a, b, strict=False, out=None)
Return the dot product of two arrays.
This function is the equivalent of `numpy.dot` that takes masked values
into account. Note that `strict` and `out` are in different position
than in the method version. In order to maintain compatibility with the
corresponding method, it is recommended that the optional arguments be
treated as keyword only. At some point that may be mandatory.
Parameters
----------
a, b : masked_array_like
Inputs arrays.
strict : bool, optional
Whether masked data are propagated (True) or set to 0 (False) for
the computation. Default is False. Propagating the mask means that
if a masked value appears in a row or column, the whole row or
column is considered masked.
out : masked_array, optional
Output argument. This must have the exact kind that would be returned
if it was not used. In particular, it must have the right type, must be
C-contiguous, and its dtype must be the dtype that would be returned
for `dot(a,b)`. This is a performance feature. Therefore, if these
conditions are not met, an exception is raised, instead of attempting
to be flexible.
.. versionadded:: 1.10.2
See Also
--------
numpy.dot : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> a = np.ma.array([[1, 2, 3], [4, 5, 6]], mask=[[1, 0, 0], [0, 0, 0]])
>>> b = np.ma.array([[1, 2], [3, 4], [5, 6]], mask=[[1, 0], [0, 0], [0, 0]])
>>> np.ma.dot(a, b)
masked_array(
data=[[21, 26],
[45, 64]],
mask=[[False, False],
[False, False]],
fill_value=999999)
>>> np.ma.dot(a, b, strict=True)
masked_array(
data=[[--, --],
[--, 64]],
mask=[[ True, True],
[ True, False]],
fill_value=999999)
ediff1d(arr, to_end=None, to_begin=None)
Compute the differences between consecutive elements of an array.
This function is the equivalent of `numpy.ediff1d` that takes masked
values into account, see `numpy.ediff1d` for details.
See Also
--------
numpy.ediff1d : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> arr = np.ma.array([1, 2, 4, 7, 0])
>>> np.ma.ediff1d(arr)
masked_array(data=[ 1, 2, 3, -7],
mask=False,
fill_value=999999)
expand_dims(a, axis)
Expand the shape of an array.
Insert a new axis that will appear at the `axis` position in the expanded
array shape.
Parameters
----------
a : array_like
Input array.
axis : int or tuple of ints
Position in the expanded axes where the new axis (or axes) is placed.
.. deprecated:: 1.13.0
Passing an axis where ``axis > a.ndim`` will be treated as
``axis == a.ndim``, and passing ``axis < -a.ndim - 1`` will
be treated as ``axis == 0``. This behavior is deprecated.
.. versionchanged:: 1.18.0
A tuple of axes is now supported. Out of range axes as
described above are now forbidden and raise an
`~exceptions.AxisError`.
Returns
-------
result : ndarray
View of `a` with the number of dimensions increased.
See Also
--------
squeeze : The inverse operation, removing singleton dimensions
reshape : Insert, remove, and combine dimensions, and resize existing ones
atleast_1d, atleast_2d, atleast_3d
Examples
--------
>>> import numpy as np
>>> x = np.array([1, 2])
>>> x.shape
(2,)
The following is equivalent to ``x[np.newaxis, :]`` or ``x[np.newaxis]``:
>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)
The following is equivalent to ``x[:, np.newaxis]``:
>>> y = np.expand_dims(x, axis=1)
>>> y
array([[1],
[2]])
>>> y.shape
(2, 1)
``axis`` may also be a tuple:
>>> y = np.expand_dims(x, axis=(0, 1))
>>> y
array([[[1, 2]]])
>>> y = np.expand_dims(x, axis=(2, 0))
>>> y
array([[[1],
[2]]])
Note that some examples may use ``None`` instead of ``np.newaxis``. These
are the same objects:
>>> np.newaxis is None
True
filled(a, fill_value=None)
Return input as an `~numpy.ndarray`, with masked values replaced by
`fill_value`.
If `a` is not a `MaskedArray`, `a` itself is returned.
If `a` is a `MaskedArray` with no masked values, then ``a.data`` is
returned.
If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to
``a.fill_value``.
Parameters
----------
a : MaskedArray or array_like
An input object.
fill_value : array_like, optional.
Can be scalar or non-scalar. If non-scalar, the
resulting filled array should be broadcastable
over input array. Default is None.
Returns
-------
a : ndarray
The filled array.
See Also
--------
compressed
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
... [1, 0, 0],
... [0, 0, 0]])
>>> x.filled()
array([[999999, 1, 2],
[999999, 4, 5],
[ 6, 7, 8]])
>>> x.filled(fill_value=333)
array([[333, 1, 2],
[333, 4, 5],
[ 6, 7, 8]])
>>> x.filled(fill_value=np.arange(3))
array([[0, 1, 2],
[0, 4, 5],
[6, 7, 8]])
fix_invalid(a, mask=np.False_, copy=True, fill_value=None)
Return input with invalid data masked and replaced by a fill value.
Invalid data means values of `nan`, `inf`, etc.
Parameters
----------
a : array_like
Input array, a (subclass of) ndarray.
mask : sequence, optional
Mask. Must be convertible to an array of booleans with the same
shape as `data`. True indicates a masked (i.e. invalid) data.
copy : bool, optional
Whether to use a copy of `a` (True) or to fix `a` in place (False).
Default is True.
fill_value : scalar, optional
Value used for fixing invalid data. Default is None, in which case
the ``a.fill_value`` is used.
Returns
-------
b : MaskedArray
The input array with invalid entries fixed.
Notes
-----
A copy is performed by default.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3)
>>> x
masked_array(data=[--, -1.0, nan, inf],
mask=[ True, False, False, False],
fill_value=1e+20)
>>> np.ma.fix_invalid(x)
masked_array(data=[--, -1.0, --, --],
mask=[ True, False, True, True],
fill_value=1e+20)
>>> fixed = np.ma.fix_invalid(x)
>>> fixed.data
array([ 1.e+00, -1.e+00, 1.e+20, 1.e+20])
>>> x.data
array([ 1., -1., nan, inf])
flatnotmasked_contiguous(a)
Find contiguous unmasked data in a masked array.
Parameters
----------
a : array_like
The input array.
Returns
-------
slice_list : list
A sorted sequence of `slice` objects (start index, end index).
.. versionchanged:: 1.15.0
Now returns an empty list instead of None for a fully masked array
See Also
--------
flatnotmasked_edges, notmasked_contiguous, notmasked_edges
clump_masked, clump_unmasked
Notes
-----
Only accepts 2-D arrays at most.
Examples
--------
>>> import numpy as np
>>> a = np.ma.arange(10)
>>> np.ma.flatnotmasked_contiguous(a)
[slice(0, 10, None)]
>>> mask = (a < 3) | (a > 8) | (a == 5)
>>> a[mask] = np.ma.masked
>>> np.array(a[~a.mask])
array([3, 4, 6, 7, 8])
>>> np.ma.flatnotmasked_contiguous(a)
[slice(3, 5, None), slice(6, 9, None)]
>>> a[:] = np.ma.masked
>>> np.ma.flatnotmasked_contiguous(a)
[]
flatnotmasked_edges(a)
Find the indices of the first and last unmasked values.
Expects a 1-D `MaskedArray`, returns None if all values are masked.
Parameters
----------
a : array_like
Input 1-D `MaskedArray`
Returns
-------
edges : ndarray or None
The indices of first and last non-masked value in the array.
Returns None if all values are masked.
See Also
--------
flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges
clump_masked, clump_unmasked
Notes
-----
Only accepts 1-D arrays.
Examples
--------
>>> import numpy as np
>>> a = np.ma.arange(10)
>>> np.ma.flatnotmasked_edges(a)
array([0, 9])
>>> mask = (a < 3) | (a > 8) | (a == 5)
>>> a[mask] = np.ma.masked
>>> np.array(a[~a.mask])
array([3, 4, 6, 7, 8])
>>> np.ma.flatnotmasked_edges(a)
array([3, 8])
>>> a[:] = np.ma.masked
>>> print(np.ma.flatnotmasked_edges(a))
None
flatten_mask(mask)
Returns a completely flattened version of the mask, where nested fields
are collapsed.
Parameters
----------
mask : array_like
Input array, which will be interpreted as booleans.
Returns
-------
flattened_mask : ndarray of bools
The flattened input.
Examples
--------
>>> import numpy as np
>>> mask = np.array([0, 0, 1])
>>> np.ma.flatten_mask(mask)
array([False, False, True])
>>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
>>> np.ma.flatten_mask(mask)
array([False, False, False, True])
>>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
>>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype)
>>> np.ma.flatten_mask(mask)
array([False, False, False, False, False, True])
flatten_structured_array(a)
Flatten a structured array.
The data type of the output is chosen such that it can represent all of the
(nested) fields.
Parameters
----------
a : structured array
Returns
-------
output : masked array or ndarray
A flattened masked array if the input is a masked array, otherwise a
standard ndarray.
Examples
--------
>>> import numpy as np
>>> ndtype = [('a', int), ('b', float)]
>>> a = np.array([(1, 1), (2, 2)], dtype=ndtype)
>>> np.ma.flatten_structured_array(a)
array([[1., 1.],
[2., 2.]])
fromflex(fxarray)
Build a masked array from a suitable flexible-type array.
The input array has to have a data-type with ``_data`` and ``_mask``
fields. This type of array is output by `MaskedArray.toflex`.
Parameters
----------
fxarray : ndarray
The structured input array, containing ``_data`` and ``_mask``
fields. If present, other fields are discarded.
Returns
-------
result : MaskedArray
The constructed masked array.
See Also
--------
MaskedArray.toflex : Build a flexible-type array from a masked array.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[0] + [1, 0] * 4)
>>> rec = x.toflex()
>>> rec
array([[(0, False), (1, True), (2, False)],
[(3, True), (4, False), (5, True)],
[(6, False), (7, True), (8, False)]],
dtype=[('_data', '<i8'), ('_mask', '?')])
>>> x2 = np.ma.fromflex(rec)
>>> x2
masked_array(
data=[[0, --, 2],
[--, 4, --],
[6, --, 8]],
mask=[[False, True, False],
[ True, False, True],
[False, True, False]],
fill_value=999999)
Extra fields can be present in the structured array but are discarded:
>>> dt = [('_data', '<i4'), ('_mask', '|b1'), ('field3', '<f4')]
>>> rec2 = np.zeros((2, 2), dtype=dt)
>>> rec2
array([[(0, False, 0.), (0, False, 0.)],
[(0, False, 0.), (0, False, 0.)]],
dtype=[('_data', '<i4'), ('_mask', '?'), ('field3', '<f4')])
>>> y = np.ma.fromflex(rec2)
>>> y
masked_array(
data=[[0, 0],
[0, 0]],
mask=[[False, False],
[False, False]],
fill_value=np.int64(999999),
dtype=int32)
getdata(a, subok=True)
Return the data of a masked array as an ndarray.
Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``,
else return `a` as a ndarray or subclass (depending on `subok`) if not.
Parameters
----------
a : array_like
Input ``MaskedArray``, alternatively a ndarray or a subclass thereof.
subok : bool
Whether to force the output to be a `pure` ndarray (False) or to
return a subclass of ndarray if appropriate (True, default).
See Also
--------
getmask : Return the mask of a masked array, or nomask.
getmaskarray : Return the mask of a masked array, or full array of False.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(
data=[[1, --],
[3, 4]],
mask=[[False, True],
[False, False]],
fill_value=2)
>>> ma.getdata(a)
array([[1, 2],
[3, 4]])
Equivalently use the ``MaskedArray`` `data` attribute.
>>> a.data
array([[1, 2],
[3, 4]])
getmask(a)
Return the mask of a masked array, or nomask.
Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the
mask is not `nomask`, else return `nomask`. To guarantee a full array
of booleans of the same shape as a, use `getmaskarray`.
Parameters
----------
a : array_like
Input `MaskedArray` for which the mask is required.
See Also
--------
getdata : Return the data of a masked array as an ndarray.
getmaskarray : Return the mask of a masked array, or full array of False.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(
data=[[1, --],
[3, 4]],
mask=[[False, True],
[False, False]],
fill_value=2)
>>> ma.getmask(a)
array([[False, True],
[False, False]])
Equivalently use the `MaskedArray` `mask` attribute.
>>> a.mask
array([[False, True],
[False, False]])
Result when mask == `nomask`
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(
data=[[1, 2],
[3, 4]],
mask=False,
fill_value=999999)
>>> ma.nomask
False
>>> ma.getmask(b) == ma.nomask
True
>>> b.mask == ma.nomask
True
getmaskarray(arr)
Return the mask of a masked array, or full boolean array of False.
Return the mask of `arr` as an ndarray if `arr` is a `MaskedArray` and
the mask is not `nomask`, else return a full boolean array of False of
the same shape as `arr`.
Parameters
----------
arr : array_like
Input `MaskedArray` for which the mask is required.
See Also
--------
getmask : Return the mask of a masked array, or nomask.
getdata : Return the data of a masked array as an ndarray.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(
data=[[1, --],
[3, 4]],
mask=[[False, True],
[False, False]],
fill_value=2)
>>> ma.getmaskarray(a)
array([[False, True],
[False, False]])
Result when mask == ``nomask``
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(
data=[[1, 2],
[3, 4]],
mask=False,
fill_value=999999)
>>> ma.getmaskarray(b)
array([[False, False],
[False, False]])
in1d(ar1, ar2, assume_unique=False, invert=False)
Test whether each element of an array is also present in a second
array.
The output is always a masked array. See `numpy.in1d` for more details.
We recommend using :func:`isin` instead of `in1d` for new code.
See Also
--------
isin : Version of this function that preserves the shape of ar1.
numpy.in1d : Equivalent function for ndarrays.
Notes
-----
.. versionadded:: 1.4.0
Examples
--------
>>> import numpy as np
>>> ar1 = np.ma.array([0, 1, 2, 5, 0])
>>> ar2 = [0, 2]
>>> np.ma.in1d(ar1, ar2)
masked_array(data=[ True, False, True, False, True],
mask=False,
fill_value=True)
inner(a, b)
inner(a, b, /)
Inner product of two arrays.
Ordinary inner product of vectors for 1-D arrays (without complex
conjugation), in higher dimensions a sum product over the last axes.
Parameters
----------
a, b : array_like
If `a` and `b` are nonscalar, their last dimensions must match.
Returns
-------
out : ndarray
If `a` and `b` are both
scalars or both 1-D arrays then a scalar is returned; otherwise
an array is returned.
``out.shape = (*a.shape[:-1], *b.shape[:-1])``
Raises
------
ValueError
If both `a` and `b` are nonscalar and their last dimensions have
different sizes.
See Also
--------
tensordot : Sum products over arbitrary axes.
dot : Generalised matrix product, using second last dimension of `b`.
einsum : Einstein summation convention.
Notes
-----
Masked values are replaced by 0.
For vectors (1-D arrays) it computes the ordinary inner-product::
np.inner(a, b) = sum(a[:]*b[:])
More generally, if ``ndim(a) = r > 0`` and ``ndim(b) = s > 0``::
np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1))
or explicitly::
np.inner(a, b)[i0,...,ir-2,j0,...,js-2]
= sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:])
In addition `a` or `b` may be scalars, in which case::
np.inner(a,b) = a*b
Examples
--------
Ordinary inner product for vectors:
>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
2
Some multidimensional examples:
>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> c = np.inner(a, b)
>>> c.shape
(2, 3)
>>> c
array([[ 14, 38, 62],
[ 86, 110, 134]])
>>> a = np.arange(2).reshape((1,1,2))
>>> b = np.arange(6).reshape((3,2))
>>> c = np.inner(a, b)
>>> c.shape
(1, 1, 3)
>>> c
array([[[1, 3, 5]]])
An example where `b` is a scalar:
>>> np.inner(np.eye(2), 7)
array([[7., 0.],
[0., 7.]])
innerproduct = inner(a, b)
inner(a, b, /)
Inner product of two arrays.
Ordinary inner product of vectors for 1-D arrays (without complex
conjugation), in higher dimensions a sum product over the last axes.
Parameters
----------
a, b : array_like
If `a` and `b` are nonscalar, their last dimensions must match.
Returns
-------
out : ndarray
If `a` and `b` are both
scalars or both 1-D arrays then a scalar is returned; otherwise
an array is returned.
``out.shape = (*a.shape[:-1], *b.shape[:-1])``
Raises
------
ValueError
If both `a` and `b` are nonscalar and their last dimensions have
different sizes.
See Also
--------
tensordot : Sum products over arbitrary axes.
dot : Generalised matrix product, using second last dimension of `b`.
einsum : Einstein summation convention.
Notes
-----
Masked values are replaced by 0.
For vectors (1-D arrays) it computes the ordinary inner-product::
np.inner(a, b) = sum(a[:]*b[:])
More generally, if ``ndim(a) = r > 0`` and ``ndim(b) = s > 0``::
np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1))
or explicitly::
np.inner(a, b)[i0,...,ir-2,j0,...,js-2]
= sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:])
In addition `a` or `b` may be scalars, in which case::
np.inner(a,b) = a*b
Examples
--------
Ordinary inner product for vectors:
>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
2
Some multidimensional examples:
>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> c = np.inner(a, b)
>>> c.shape
(2, 3)
>>> c
array([[ 14, 38, 62],
[ 86, 110, 134]])
>>> a = np.arange(2).reshape((1,1,2))
>>> b = np.arange(6).reshape((3,2))
>>> c = np.inner(a, b)
>>> c.shape
(1, 1, 3)
>>> c
array([[[1, 3, 5]]])
An example where `b` is a scalar:
>>> np.inner(np.eye(2), 7)
array([[7., 0.],
[0., 7.]])
intersect1d(ar1, ar2, assume_unique=False)
Returns the unique elements common to both arrays.
Masked values are considered equal one to the other.
The output is always a masked array.
See `numpy.intersect1d` for more details.
See Also
--------
numpy.intersect1d : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([1, 3, 3, 3], mask=[0, 0, 0, 1])
>>> y = np.ma.array([3, 1, 1, 1], mask=[0, 0, 0, 1])
>>> np.ma.intersect1d(x, y)
masked_array(data=[1, 3, --],
mask=[False, False, True],
fill_value=999999)
isMA = isMaskedArray(x)
Test whether input is an instance of MaskedArray.
This function returns True if `x` is an instance of MaskedArray
and returns False otherwise. Any object is accepted as input.
Parameters
----------
x : object
Object to test.
Returns
-------
result : bool
True if `x` is a MaskedArray.
See Also
--------
isMA : Alias to isMaskedArray.
isarray : Alias to isMaskedArray.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.eye(3, 3)
>>> a
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> m = ma.masked_values(a, 0)
>>> m
masked_array(
data=[[1.0, --, --],
[--, 1.0, --],
[--, --, 1.0]],
mask=[[False, True, True],
[ True, False, True],
[ True, True, False]],
fill_value=0.0)
>>> ma.isMaskedArray(a)
False
>>> ma.isMaskedArray(m)
True
>>> ma.isMaskedArray([0, 1, 2])
False
isMaskedArray(x)
Test whether input is an instance of MaskedArray.
This function returns True if `x` is an instance of MaskedArray
and returns False otherwise. Any object is accepted as input.
Parameters
----------
x : object
Object to test.
Returns
-------
result : bool
True if `x` is a MaskedArray.
See Also
--------
isMA : Alias to isMaskedArray.
isarray : Alias to isMaskedArray.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.eye(3, 3)
>>> a
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> m = ma.masked_values(a, 0)
>>> m
masked_array(
data=[[1.0, --, --],
[--, 1.0, --],
[--, --, 1.0]],
mask=[[False, True, True],
[ True, False, True],
[ True, True, False]],
fill_value=0.0)
>>> ma.isMaskedArray(a)
False
>>> ma.isMaskedArray(m)
True
>>> ma.isMaskedArray([0, 1, 2])
False
is_mask(m)
Return True if m is a valid, standard mask.
This function does not check the contents of the input, only that the
type is MaskType. In particular, this function returns False if the
mask has a flexible dtype.
Parameters
----------
m : array_like
Array to test.
Returns
-------
result : bool
True if `m.dtype.type` is MaskType, False otherwise.
See Also
--------
ma.isMaskedArray : Test whether input is an instance of MaskedArray.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> m = ma.masked_equal([0, 1, 0, 2, 3], 0)
>>> m
masked_array(data=[--, 1, --, 2, 3],
mask=[ True, False, True, False, False],
fill_value=0)
>>> ma.is_mask(m)
False
>>> ma.is_mask(m.mask)
True
Input must be an ndarray (or have similar attributes)
for it to be considered a valid mask.
>>> m = [False, True, False]
>>> ma.is_mask(m)
False
>>> m = np.array([False, True, False])
>>> m
array([False, True, False])
>>> ma.is_mask(m)
True
Arrays with complex dtypes don't return True.
>>> dtype = np.dtype({'names':['monty', 'pithon'],
... 'formats':[bool, bool]})
>>> dtype
dtype([('monty', '|b1'), ('pithon', '|b1')])
>>> m = np.array([(True, False), (False, True), (True, False)],
... dtype=dtype)
>>> m
array([( True, False), (False, True), ( True, False)],
dtype=[('monty', '?'), ('pithon', '?')])
>>> ma.is_mask(m)
False
is_masked(x)
Determine whether input has masked values.
Accepts any object as input, but always returns False unless the
input is a MaskedArray containing masked values.
Parameters
----------
x : array_like
Array to check for masked values.
Returns
-------
result : bool
True if `x` is a MaskedArray with masked values, False otherwise.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = ma.masked_equal([0, 1, 0, 2, 3], 0)
>>> x
masked_array(data=[--, 1, --, 2, 3],
mask=[ True, False, True, False, False],
fill_value=0)
>>> ma.is_masked(x)
True
>>> x = ma.masked_equal([0, 1, 0, 2, 3], 42)
>>> x
masked_array(data=[0, 1, 0, 2, 3],
mask=False,
fill_value=42)
>>> ma.is_masked(x)
False
Always returns False if `x` isn't a MaskedArray.
>>> x = [False, True, False]
>>> ma.is_masked(x)
False
>>> x = 'a string'
>>> ma.is_masked(x)
False
isarray = isMaskedArray(x)
Test whether input is an instance of MaskedArray.
This function returns True if `x` is an instance of MaskedArray
and returns False otherwise. Any object is accepted as input.
Parameters
----------
x : object
Object to test.
Returns
-------
result : bool
True if `x` is a MaskedArray.
See Also
--------
isMA : Alias to isMaskedArray.
isarray : Alias to isMaskedArray.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.eye(3, 3)
>>> a
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> m = ma.masked_values(a, 0)
>>> m
masked_array(
data=[[1.0, --, --],
[--, 1.0, --],
[--, --, 1.0]],
mask=[[False, True, True],
[ True, False, True],
[ True, True, False]],
fill_value=0.0)
>>> ma.isMaskedArray(a)
False
>>> ma.isMaskedArray(m)
True
>>> ma.isMaskedArray([0, 1, 2])
False
isin(element, test_elements, assume_unique=False, invert=False)
Calculates `element in test_elements`, broadcasting over
`element` only.
The output is always a masked array of the same shape as `element`.
See `numpy.isin` for more details.
See Also
--------
in1d : Flattened version of this function.
numpy.isin : Equivalent function for ndarrays.
Notes
-----
.. versionadded:: 1.13.0
Examples
--------
>>> import numpy as np
>>> element = np.ma.array([1, 2, 3, 4, 5, 6])
>>> test_elements = [0, 2]
>>> np.ma.isin(element, test_elements)
masked_array(data=[False, True, False, False, False, False],
mask=False,
fill_value=True)
left_shift(a, n)
Shift the bits of an integer to the left.
This is the masked array version of `numpy.left_shift`, for details
see that function.
See Also
--------
numpy.left_shift
Examples
--------
Shift with a masked array:
>>> arr = np.ma.array([10, 20, 30], mask=[False, True, False])
>>> np.ma.left_shift(arr, 1)
masked_array(data=[20, --, 60],
mask=[False, True, False],
fill_value=999999)
Large shift:
>>> np.ma.left_shift(10, 10)
masked_array(data=10240,
mask=False,
fill_value=999999)
Shift with a scalar and an array:
>>> scalar = 10
>>> arr = np.ma.array([1, 2, 3], mask=[False, True, False])
>>> np.ma.left_shift(scalar, arr)
masked_array(data=[20, --, 80],
mask=[False, True, False],
fill_value=999999)
make_mask(m, copy=False, shrink=True, dtype=<class 'numpy.bool'>)
Create a boolean mask from an array.
Return `m` as a boolean mask, creating a copy if necessary or requested.
The function can accept any sequence that is convertible to integers,
or ``nomask``. Does not require that contents must be 0s and 1s, values
of 0 are interpreted as False, everything else as True.
Parameters
----------
m : array_like
Potential mask.
copy : bool, optional
Whether to return a copy of `m` (True) or `m` itself (False).
shrink : bool, optional
Whether to shrink `m` to ``nomask`` if all its values are False.
dtype : dtype, optional
Data-type of the output mask. By default, the output mask has a
dtype of MaskType (bool). If the dtype is flexible, each field has
a boolean dtype. This is ignored when `m` is ``nomask``, in which
case ``nomask`` is always returned.
Returns
-------
result : ndarray
A boolean mask derived from `m`.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> m = [True, False, True, True]
>>> ma.make_mask(m)
array([ True, False, True, True])
>>> m = [1, 0, 1, 1]
>>> ma.make_mask(m)
array([ True, False, True, True])
>>> m = [1, 0, 2, -3]
>>> ma.make_mask(m)
array([ True, False, True, True])
Effect of the `shrink` parameter.
>>> m = np.zeros(4)
>>> m
array([0., 0., 0., 0.])
>>> ma.make_mask(m)
False
>>> ma.make_mask(m, shrink=False)
array([False, False, False, False])
Using a flexible `dtype`.
>>> m = [1, 0, 1, 1]
>>> n = [0, 1, 0, 0]
>>> arr = []
>>> for man, mouse in zip(m, n):
... arr.append((man, mouse))
>>> arr
[(1, 0), (0, 1), (1, 0), (1, 0)]
>>> dtype = np.dtype({'names':['man', 'mouse'],
... 'formats':[np.int64, np.int64]})
>>> arr = np.array(arr, dtype=dtype)
>>> arr
array([(1, 0), (0, 1), (1, 0), (1, 0)],
dtype=[('man', '<i8'), ('mouse', '<i8')])
>>> ma.make_mask(arr, dtype=dtype)
array([(True, False), (False, True), (True, False), (True, False)],
dtype=[('man', '|b1'), ('mouse', '|b1')])
make_mask_descr(ndtype)
Construct a dtype description list from a given dtype.
Returns a new dtype object, with the type of all fields in `ndtype` to a
boolean type. Field names are not altered.
Parameters
----------
ndtype : dtype
The dtype to convert.
Returns
-------
result : dtype
A dtype that looks like `ndtype`, the type of all fields is boolean.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> dtype = np.dtype({'names':['foo', 'bar'],
... 'formats':[np.float32, np.int64]})
>>> dtype
dtype([('foo', '<f4'), ('bar', '<i8')])
>>> ma.make_mask_descr(dtype)
dtype([('foo', '|b1'), ('bar', '|b1')])
>>> ma.make_mask_descr(np.float32)
dtype('bool')
make_mask_none(newshape, dtype=None)
Return a boolean mask of the given shape, filled with False.
This function returns a boolean ndarray with all entries False, that can
be used in common mask manipulations. If a complex dtype is specified, the
type of each field is converted to a boolean type.
Parameters
----------
newshape : tuple
A tuple indicating the shape of the mask.
dtype : {None, dtype}, optional
If None, use a MaskType instance. Otherwise, use a new datatype with
the same fields as `dtype`, converted to boolean types.
Returns
-------
result : ndarray
An ndarray of appropriate shape and dtype, filled with False.
See Also
--------
make_mask : Create a boolean mask from an array.
make_mask_descr : Construct a dtype description list from a given dtype.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> ma.make_mask_none((3,))
array([False, False, False])
Defining a more complex dtype.
>>> dtype = np.dtype({'names':['foo', 'bar'],
... 'formats':[np.float32, np.int64]})
>>> dtype
dtype([('foo', '<f4'), ('bar', '<i8')])
>>> ma.make_mask_none((3,), dtype=dtype)
array([(False, False), (False, False), (False, False)],
dtype=[('foo', '|b1'), ('bar', '|b1')])
mask_cols(a, axis=<no value>)
Mask columns of a 2D array that contain masked values.
This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1.
See Also
--------
mask_rowcols : Mask rows and/or columns of a 2D array.
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy as np
>>> a = np.zeros((3, 3), dtype=int)
>>> a[1, 1] = 1
>>> a
array([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]])
>>> a = np.ma.masked_equal(a, 1)
>>> a
masked_array(
data=[[0, 0, 0],
[0, --, 0],
[0, 0, 0]],
mask=[[False, False, False],
[False, True, False],
[False, False, False]],
fill_value=1)
>>> np.ma.mask_cols(a)
masked_array(
data=[[0, --, 0],
[0, --, 0],
[0, --, 0]],
mask=[[False, True, False],
[False, True, False],
[False, True, False]],
fill_value=1)
mask_or(m1, m2, copy=False, shrink=True)
Combine two masks with the ``logical_or`` operator.
The result may be a view on `m1` or `m2` if the other is `nomask`
(i.e. False).
Parameters
----------
m1, m2 : array_like
Input masks.
copy : bool, optional
If copy is False and one of the inputs is `nomask`, return a view
of the other input mask. Defaults to False.
shrink : bool, optional
Whether to shrink the output to `nomask` if all its values are
False. Defaults to True.
Returns
-------
mask : output mask
The result masks values that are masked in either `m1` or `m2`.
Raises
------
ValueError
If `m1` and `m2` have different flexible dtypes.
Examples
--------
>>> import numpy as np
>>> m1 = np.ma.make_mask([0, 1, 1, 0])
>>> m2 = np.ma.make_mask([1, 0, 0, 0])
>>> np.ma.mask_or(m1, m2)
array([ True, True, True, False])
mask_rowcols(a, axis=None)
Mask rows and/or columns of a 2D array that contain masked values.
Mask whole rows and/or columns of a 2D array that contain
masked values. The masking behavior is selected using the
`axis` parameter.
- If `axis` is None, rows *and* columns are masked.
- If `axis` is 0, only rows are masked.
- If `axis` is 1 or -1, only columns are masked.
Parameters
----------
a : array_like, MaskedArray
The array to mask. If not a MaskedArray instance (or if no array
elements are masked), the result is a MaskedArray with `mask` set
to `nomask` (False). Must be a 2D array.
axis : int, optional
Axis along which to perform the operation. If None, applies to a
flattened version of the array.
Returns
-------
a : MaskedArray
A modified version of the input array, masked depending on the value
of the `axis` parameter.
Raises
------
NotImplementedError
If input array `a` is not 2D.
See Also
--------
mask_rows : Mask rows of a 2D array that contain masked values.
mask_cols : Mask cols of a 2D array that contain masked values.
masked_where : Mask where a condition is met.
Notes
-----
The input array's mask is modified by this function.
Examples
--------
>>> import numpy as np
>>> a = np.zeros((3, 3), dtype=int)
>>> a[1, 1] = 1
>>> a
array([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]])
>>> a = np.ma.masked_equal(a, 1)
>>> a
masked_array(
data=[[0, 0, 0],
[0, --, 0],
[0, 0, 0]],
mask=[[False, False, False],
[False, True, False],
[False, False, False]],
fill_value=1)
>>> np.ma.mask_rowcols(a)
masked_array(
data=[[0, --, 0],
[--, --, --],
[0, --, 0]],
mask=[[False, True, False],
[ True, True, True],
[False, True, False]],
fill_value=1)
mask_rows(a, axis=<no value>)
Mask rows of a 2D array that contain masked values.
This function is a shortcut to ``mask_rowcols`` with `axis` equal to 0.
See Also
--------
mask_rowcols : Mask rows and/or columns of a 2D array.
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy as np
>>> a = np.zeros((3, 3), dtype=int)
>>> a[1, 1] = 1
>>> a
array([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]])
>>> a = np.ma.masked_equal(a, 1)
>>> a
masked_array(
data=[[0, 0, 0],
[0, --, 0],
[0, 0, 0]],
mask=[[False, False, False],
[False, True, False],
[False, False, False]],
fill_value=1)
>>> np.ma.mask_rows(a)
masked_array(
data=[[0, 0, 0],
[--, --, --],
[0, 0, 0]],
mask=[[False, False, False],
[ True, True, True],
[False, False, False]],
fill_value=1)
masked_all(shape, dtype=<class 'float'>)
Empty masked array with all elements masked.
Return an empty masked array of the given shape and dtype, where all the
data are masked.
Parameters
----------
shape : int or tuple of ints
Shape of the required MaskedArray, e.g., ``(2, 3)`` or ``2``.
dtype : dtype, optional
Data type of the output.
Returns
-------
a : MaskedArray
A masked array with all data masked.
See Also
--------
masked_all_like : Empty masked array modelled on an existing array.
Notes
-----
Unlike other masked array creation functions (e.g. `numpy.ma.zeros`,
`numpy.ma.ones`, `numpy.ma.full`), `masked_all` does not initialize the
values of the array, and may therefore be marginally faster. However,
the values stored in the newly allocated array are arbitrary. For
reproducible behavior, be sure to set each element of the array before
reading.
Examples
--------
>>> import numpy as np
>>> np.ma.masked_all((3, 3))
masked_array(
data=[[--, --, --],
[--, --, --],
[--, --, --]],
mask=[[ True, True, True],
[ True, True, True],
[ True, True, True]],
fill_value=1e+20,
dtype=float64)
The `dtype` parameter defines the underlying data type.
>>> a = np.ma.masked_all((3, 3))
>>> a.dtype
dtype('float64')
>>> a = np.ma.masked_all((3, 3), dtype=np.int32)
>>> a.dtype
dtype('int32')
masked_all_like(arr)
Empty masked array with the properties of an existing array.
Return an empty masked array of the same shape and dtype as
the array `arr`, where all the data are masked.
Parameters
----------
arr : ndarray
An array describing the shape and dtype of the required MaskedArray.
Returns
-------
a : MaskedArray
A masked array with all data masked.
Raises
------
AttributeError
If `arr` doesn't have a shape attribute (i.e. not an ndarray)
See Also
--------
masked_all : Empty masked array with all elements masked.
Notes
-----
Unlike other masked array creation functions (e.g. `numpy.ma.zeros_like`,
`numpy.ma.ones_like`, `numpy.ma.full_like`), `masked_all_like` does not
initialize the values of the array, and may therefore be marginally
faster. However, the values stored in the newly allocated array are
arbitrary. For reproducible behavior, be sure to set each element of the
array before reading.
Examples
--------
>>> import numpy as np
>>> arr = np.zeros((2, 3), dtype=np.float32)
>>> arr
array([[0., 0., 0.],
[0., 0., 0.]], dtype=float32)
>>> np.ma.masked_all_like(arr)
masked_array(
data=[[--, --, --],
[--, --, --]],
mask=[[ True, True, True],
[ True, True, True]],
fill_value=np.float64(1e+20),
dtype=float32)
The dtype of the masked array matches the dtype of `arr`.
>>> arr.dtype
dtype('float32')
>>> np.ma.masked_all_like(arr).dtype
dtype('float32')
masked_equal(x, value, copy=True)
Mask an array where equal to a given value.
Return a MaskedArray, masked where the data in array `x` are
equal to `value`. The fill_value of the returned MaskedArray
is set to `value`.
For floating point arrays, consider using ``masked_values(x, value)``.
See Also
--------
masked_where : Mask where a condition is met.
masked_values : Mask using floating point equality.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_equal(a, 2)
masked_array(data=[0, 1, --, 3],
mask=[False, False, True, False],
fill_value=2)
masked_greater(x, value, copy=True)
Mask an array where greater than a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x > value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_greater(a, 2)
masked_array(data=[0, 1, 2, --],
mask=[False, False, False, True],
fill_value=999999)
masked_greater_equal(x, value, copy=True)
Mask an array where greater than or equal to a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x >= value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_greater_equal(a, 2)
masked_array(data=[0, 1, --, --],
mask=[False, False, True, True],
fill_value=999999)
masked_inside(x, v1, v2, copy=True)
Mask an array inside a given interval.
Shortcut to ``masked_where``, where `condition` is True for `x` inside
the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2`
can be given in either order.
See Also
--------
masked_where : Mask where a condition is met.
Notes
-----
The array `x` is prefilled with its filling value.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
>>> ma.masked_inside(x, -0.3, 0.3)
masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
mask=[False, False, True, True, False, False],
fill_value=1e+20)
The order of `v1` and `v2` doesn't matter.
>>> ma.masked_inside(x, 0.3, -0.3)
masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
mask=[False, False, True, True, False, False],
fill_value=1e+20)
masked_invalid(a, copy=True)
Mask an array where invalid values occur (NaNs or infs).
This function is a shortcut to ``masked_where``, with
`condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved.
Only applies to arrays with a dtype where NaNs or infs make sense
(i.e. floating point types), but accepts any array_like object.
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.arange(5, dtype=float)
>>> a[2] = np.nan
>>> a[3] = np.inf
>>> a
array([ 0., 1., nan, inf, 4.])
>>> ma.masked_invalid(a)
masked_array(data=[0.0, 1.0, --, --, 4.0],
mask=[False, False, True, True, False],
fill_value=1e+20)
masked_less(x, value, copy=True)
Mask an array where less than a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x < value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_less(a, 2)
masked_array(data=[--, --, 2, 3],
mask=[ True, True, False, False],
fill_value=999999)
masked_less_equal(x, value, copy=True)
Mask an array where less than or equal to a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x <= value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_less_equal(a, 2)
masked_array(data=[--, --, --, 3],
mask=[ True, True, True, False],
fill_value=999999)
masked_not_equal(x, value, copy=True)
Mask an array where *not* equal to a given value.
This function is a shortcut to ``masked_where``, with
`condition` = (x != value).
See Also
--------
masked_where : Mask where a condition is met.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_not_equal(a, 2)
masked_array(data=[--, --, 2, --],
mask=[ True, True, False, True],
fill_value=999999)
masked_object(x, value, copy=True, shrink=True)
Mask the array `x` where the data are exactly equal to value.
This function is similar to `masked_values`, but only suitable
for object arrays: for floating point, use `masked_values` instead.
Parameters
----------
x : array_like
Array to mask
value : object
Comparison value
copy : {True, False}, optional
Whether to return a copy of `x`.
shrink : {True, False}, optional
Whether to collapse a mask full of False to nomask
Returns
-------
result : MaskedArray
The result of masking `x` where equal to `value`.
See Also
--------
masked_where : Mask where a condition is met.
masked_equal : Mask where equal to a given value (integers).
masked_values : Mask using floating point equality.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> food = np.array(['green_eggs', 'ham'], dtype=object)
>>> # don't eat spoiled food
>>> eat = ma.masked_object(food, 'green_eggs')
>>> eat
masked_array(data=[--, 'ham'],
mask=[ True, False],
fill_value='green_eggs',
dtype=object)
>>> # plain ol` ham is boring
>>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object)
>>> eat = ma.masked_object(fresh_food, 'green_eggs')
>>> eat
masked_array(data=['cheese', 'ham', 'pineapple'],
mask=False,
fill_value='green_eggs',
dtype=object)
Note that `mask` is set to ``nomask`` if possible.
>>> eat
masked_array(data=['cheese', 'ham', 'pineapple'],
mask=False,
fill_value='green_eggs',
dtype=object)
masked_outside(x, v1, v2, copy=True)
Mask an array outside a given interval.
Shortcut to ``masked_where``, where `condition` is True for `x` outside
the interval [v1,v2] (x < v1)|(x > v2).
The boundaries `v1` and `v2` can be given in either order.
See Also
--------
masked_where : Mask where a condition is met.
Notes
-----
The array `x` is prefilled with its filling value.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
>>> ma.masked_outside(x, -0.3, 0.3)
masked_array(data=[--, --, 0.01, 0.2, --, --],
mask=[ True, True, False, False, True, True],
fill_value=1e+20)
The order of `v1` and `v2` doesn't matter.
>>> ma.masked_outside(x, 0.3, -0.3)
masked_array(data=[--, --, 0.01, 0.2, --, --],
mask=[ True, True, False, False, True, True],
fill_value=1e+20)
masked_values(x, value, rtol=1e-05, atol=1e-08, copy=True, shrink=True)
Mask using floating point equality.
Return a MaskedArray, masked where the data in array `x` are approximately
equal to `value`, determined using `isclose`. The default tolerances for
`masked_values` are the same as those for `isclose`.
For integer types, exact equality is used, in the same way as
`masked_equal`.
The fill_value is set to `value` and the mask is set to ``nomask`` if
possible.
Parameters
----------
x : array_like
Array to mask.
value : float
Masking value.
rtol, atol : float, optional
Tolerance parameters passed on to `isclose`
copy : bool, optional
Whether to return a copy of `x`.
shrink : bool, optional
Whether to collapse a mask full of False to ``nomask``.
Returns
-------
result : MaskedArray
The result of masking `x` where approximately equal to `value`.
See Also
--------
masked_where : Mask where a condition is met.
masked_equal : Mask where equal to a given value (integers).
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = np.array([1, 1.1, 2, 1.1, 3])
>>> ma.masked_values(x, 1.1)
masked_array(data=[1.0, --, 2.0, --, 3.0],
mask=[False, True, False, True, False],
fill_value=1.1)
Note that `mask` is set to ``nomask`` if possible.
>>> ma.masked_values(x, 2.1)
masked_array(data=[1. , 1.1, 2. , 1.1, 3. ],
mask=False,
fill_value=2.1)
Unlike `masked_equal`, `masked_values` can perform approximate equalities.
>>> ma.masked_values(x, 2.1, atol=1e-1)
masked_array(data=[1.0, 1.1, --, 1.1, 3.0],
mask=[False, False, True, False, False],
fill_value=2.1)
masked_where(condition, a, copy=True)
Mask an array where a condition is met.
Return `a` as an array masked where `condition` is True.
Any masked values of `a` or `condition` are also masked in the output.
Parameters
----------
condition : array_like
Masking condition. When `condition` tests floating point values for
equality, consider using ``masked_values`` instead.
a : array_like
Array to mask.
copy : bool
If True (default) make a copy of `a` in the result. If False modify
`a` in place and return a view.
Returns
-------
result : MaskedArray
The result of masking `a` where `condition` is True.
See Also
--------
masked_values : Mask using floating point equality.
masked_equal : Mask where equal to a given value.
masked_not_equal : Mask where *not* equal to a given value.
masked_less_equal : Mask where less than or equal to a given value.
masked_greater_equal : Mask where greater than or equal to a given value.
masked_less : Mask where less than a given value.
masked_greater : Mask where greater than a given value.
masked_inside : Mask inside a given interval.
masked_outside : Mask outside a given interval.
masked_invalid : Mask invalid values (NaNs or infs).
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_where(a <= 2, a)
masked_array(data=[--, --, --, 3],
mask=[ True, True, True, False],
fill_value=999999)
Mask array `b` conditional on `a`.
>>> b = ['a', 'b', 'c', 'd']
>>> ma.masked_where(a == 2, b)
masked_array(data=['a', 'b', --, 'd'],
mask=[False, False, True, False],
fill_value='N/A',
dtype='<U1')
Effect of the `copy` argument.
>>> c = ma.masked_where(a <= 2, a)
>>> c
masked_array(data=[--, --, --, 3],
mask=[ True, True, True, False],
fill_value=999999)
>>> c[0] = 99
>>> c
masked_array(data=[99, --, --, 3],
mask=[False, True, True, False],
fill_value=999999)
>>> a
array([0, 1, 2, 3])
>>> c = ma.masked_where(a <= 2, a, copy=False)
>>> c[0] = 99
>>> c
masked_array(data=[99, --, --, 3],
mask=[False, True, True, False],
fill_value=999999)
>>> a
array([99, 1, 2, 3])
When `condition` or `a` contain masked values.
>>> a = np.arange(4)
>>> a = ma.masked_where(a == 2, a)
>>> a
masked_array(data=[0, 1, --, 3],
mask=[False, False, True, False],
fill_value=999999)
>>> b = np.arange(4)
>>> b = ma.masked_where(b == 0, b)
>>> b
masked_array(data=[--, 1, 2, 3],
mask=[ True, False, False, False],
fill_value=999999)
>>> ma.masked_where(a == 3, b)
masked_array(data=[--, 1, --, --],
mask=[ True, False, True, True],
fill_value=999999)
max(obj, axis=None, out=None, fill_value=None, keepdims=<no value>)
Return the maximum along a given axis.
Parameters
----------
axis : None or int or tuple of ints, optional
Axis along which to operate. By default, ``axis`` is None and the
flattened input is used.
.. versionadded:: 1.7.0
If this is a tuple of ints, the maximum is selected over multiple
axes, instead of a single axis or all the axes as before.
out : array_like, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
fill_value : scalar or None, optional
Value used to fill in the masked values.
If None, use the output of maximum_fill_value().
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.
Returns
-------
amax : array_like
New array holding the result.
If ``out`` was specified, ``out`` is returned.
See Also
--------
ma.maximum_fill_value
Returns the maximum filling value for a given datatype.
Examples
--------
>>> import numpy.ma as ma
>>> x = [[-1., 2.5], [4., -2.], [3., 0.]]
>>> mask = [[0, 0], [1, 0], [1, 0]]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(
data=[[-1.0, 2.5],
[--, -2.0],
[--, 0.0]],
mask=[[False, False],
[ True, False],
[ True, False]],
fill_value=1e+20)
>>> ma.max(masked_x)
2.5
>>> ma.max(masked_x, axis=0)
masked_array(data=[-1.0, 2.5],
mask=[False, False],
fill_value=1e+20)
>>> ma.max(masked_x, axis=1, keepdims=True)
masked_array(
data=[[2.5],
[-2.0],
[0.0]],
mask=[[False],
[False],
[False]],
fill_value=1e+20)
>>> mask = [[1, 1], [1, 1], [1, 1]]
>>> masked_x = ma.masked_array(x, mask)
>>> ma.max(masked_x, axis=1)
masked_array(data=[--, --, --],
mask=[ True, True, True],
fill_value=1e+20,
dtype=float64)
maximum_fill_value(obj)
Return the minimum value that can be represented by the dtype of an object.
This function is useful for calculating a fill value suitable for
taking the maximum of an array with a given dtype.
Parameters
----------
obj : ndarray, dtype or scalar
An object that can be queried for it's numeric type.
Returns
-------
val : scalar
The minimum representable value.
Raises
------
TypeError
If `obj` isn't a suitable numeric type.
See Also
--------
minimum_fill_value : The inverse function.
set_fill_value : Set the filling value of a masked array.
MaskedArray.fill_value : Return current fill value.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.int8()
>>> ma.maximum_fill_value(a)
-128
>>> a = np.int32()
>>> ma.maximum_fill_value(a)
-2147483648
An array of numeric data can also be passed.
>>> a = np.array([1, 2, 3], dtype=np.int8)
>>> ma.maximum_fill_value(a)
-128
>>> a = np.array([1, 2, 3], dtype=np.float32)
>>> ma.maximum_fill_value(a)
-inf
median(a, axis=None, out=None, overwrite_input=False, keepdims=False)
Compute the median along the specified axis.
Returns the median of the array elements.
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : int, optional
Axis along which the medians are computed. The default (None) is
to compute the median along a flattened version of the array.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
overwrite_input : bool, optional
If True, then allow use of memory of input array (a) for
calculations. The input array will be modified by the call to
median. This will save memory when you do not need to preserve
the contents of the input array. Treat the input as undefined,
but it will probably be fully or partially sorted. Default is
False. Note that, if `overwrite_input` is True, and the input
is not already an `ndarray`, an error will be raised.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
.. versionadded:: 1.10.0
Returns
-------
median : ndarray
A new array holding the result is returned unless out is
specified, in which case a reference to out is returned.
Return data-type is `float64` for integers and floats smaller than
`float64`, or the input data-type, otherwise.
See Also
--------
mean
Notes
-----
Given a vector ``V`` with ``N`` non masked values, the median of ``V``
is the middle value of a sorted copy of ``V`` (``Vs``) - i.e.
``Vs[(N-1)/2]``, when ``N`` is odd, or ``{Vs[N/2 - 1] + Vs[N/2]}/2``
when ``N`` is even.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array(np.arange(8), mask=[0]*4 + [1]*4)
>>> np.ma.median(x)
1.5
>>> x = np.ma.array(np.arange(10).reshape(2, 5), mask=[0]*6 + [1]*4)
>>> np.ma.median(x)
2.5
>>> np.ma.median(x, axis=-1, overwrite_input=True)
masked_array(data=[2.0, 5.0],
mask=[False, False],
fill_value=1e+20)
min(obj, axis=None, out=None, fill_value=None, keepdims=<no value>)
Return the minimum along a given axis.
Parameters
----------
axis : None or int or tuple of ints, optional
Axis along which to operate. By default, ``axis`` is None and the
flattened input is used.
.. versionadded:: 1.7.0
If this is a tuple of ints, the minimum is selected over multiple
axes, instead of a single axis or all the axes as before.
out : array_like, optional
Alternative output array in which to place the result. Must be of
the same shape and buffer length as the expected output.
fill_value : scalar or None, optional
Value used to fill in the masked values.
If None, use the output of `minimum_fill_value`.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.
Returns
-------
amin : array_like
New array holding the result.
If ``out`` was specified, ``out`` is returned.
See Also
--------
ma.minimum_fill_value
Returns the minimum filling value for a given datatype.
Examples
--------
>>> import numpy.ma as ma
>>> x = [[1., -2., 3.], [0.2, -0.7, 0.1]]
>>> mask = [[1, 1, 0], [0, 0, 1]]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(
data=[[--, --, 3.0],
[0.2, -0.7, --]],
mask=[[ True, True, False],
[False, False, True]],
fill_value=1e+20)
>>> ma.min(masked_x)
-0.7
>>> ma.min(masked_x, axis=-1)
masked_array(data=[3.0, -0.7],
mask=[False, False],
fill_value=1e+20)
>>> ma.min(masked_x, axis=0, keepdims=True)
masked_array(data=[[0.2, -0.7, 3.0]],
mask=[[False, False, False]],
fill_value=1e+20)
>>> mask = [[1, 1, 1,], [1, 1, 1]]
>>> masked_x = ma.masked_array(x, mask)
>>> ma.min(masked_x, axis=0)
masked_array(data=[--, --, --],
mask=[ True, True, True],
fill_value=1e+20,
dtype=float64)
minimum_fill_value(obj)
Return the maximum value that can be represented by the dtype of an object.
This function is useful for calculating a fill value suitable for
taking the minimum of an array with a given dtype.
Parameters
----------
obj : ndarray, dtype or scalar
An object that can be queried for it's numeric type.
Returns
-------
val : scalar
The maximum representable value.
Raises
------
TypeError
If `obj` isn't a suitable numeric type.
See Also
--------
maximum_fill_value : The inverse function.
set_fill_value : Set the filling value of a masked array.
MaskedArray.fill_value : Return current fill value.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.int8()
>>> ma.minimum_fill_value(a)
127
>>> a = np.int32()
>>> ma.minimum_fill_value(a)
2147483647
An array of numeric data can also be passed.
>>> a = np.array([1, 2, 3], dtype=np.int8)
>>> ma.minimum_fill_value(a)
127
>>> a = np.array([1, 2, 3], dtype=np.float32)
>>> ma.minimum_fill_value(a)
inf
ndenumerate(a, compressed=True)
Multidimensional index iterator.
Return an iterator yielding pairs of array coordinates and values,
skipping elements that are masked. With `compressed=False`,
`ma.masked` is yielded as the value of masked elements. This
behavior differs from that of `numpy.ndenumerate`, which yields the
value of the underlying data array.
Notes
-----
.. versionadded:: 1.23.0
Parameters
----------
a : array_like
An array with (possibly) masked elements.
compressed : bool, optional
If True (default), masked elements are skipped.
See Also
--------
numpy.ndenumerate : Equivalent function ignoring any mask.
Examples
--------
>>> import numpy as np
>>> a = np.ma.arange(9).reshape((3, 3))
>>> a[1, 0] = np.ma.masked
>>> a[1, 2] = np.ma.masked
>>> a[2, 1] = np.ma.masked
>>> a
masked_array(
data=[[0, 1, 2],
[--, 4, --],
[6, --, 8]],
mask=[[False, False, False],
[ True, False, True],
[False, True, False]],
fill_value=999999)
>>> for index, x in np.ma.ndenumerate(a):
... print(index, x)
(0, 0) 0
(0, 1) 1
(0, 2) 2
(1, 1) 4
(2, 0) 6
(2, 2) 8
>>> for index, x in np.ma.ndenumerate(a, compressed=False):
... print(index, x)
(0, 0) 0
(0, 1) 1
(0, 2) 2
(1, 0) --
(1, 1) 4
(1, 2) --
(2, 0) 6
(2, 1) --
(2, 2) 8
ndim(obj)
Return the number of dimensions of an array.
Parameters
----------
a : array_like
Input array. If it is not already an ndarray, a conversion is
attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in `a`. Scalars are zero-dimensional.
See Also
--------
ndarray.ndim : equivalent method
shape : dimensions of array
ndarray.shape : dimensions of array
Examples
--------
>>> import numpy as np
>>> np.ndim([[1,2,3],[4,5,6]])
2
>>> np.ndim(np.array([[1,2,3],[4,5,6]]))
2
>>> np.ndim(1)
0
notmasked_contiguous(a, axis=None)
Find contiguous unmasked data in a masked array along the given axis.
Parameters
----------
a : array_like
The input array.
axis : int, optional
Axis along which to perform the operation.
If None (default), applies to a flattened version of the array, and this
is the same as `flatnotmasked_contiguous`.
Returns
-------
endpoints : list
A list of slices (start and end indexes) of unmasked indexes
in the array.
If the input is 2d and axis is specified, the result is a list of lists.
See Also
--------
flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges
clump_masked, clump_unmasked
Notes
-----
Only accepts 2-D arrays at most.
Examples
--------
>>> import numpy as np
>>> a = np.arange(12).reshape((3, 4))
>>> mask = np.zeros_like(a)
>>> mask[1:, :-1] = 1; mask[0, 1] = 1; mask[-1, 0] = 0
>>> ma = np.ma.array(a, mask=mask)
>>> ma
masked_array(
data=[[0, --, 2, 3],
[--, --, --, 7],
[8, --, --, 11]],
mask=[[False, True, False, False],
[ True, True, True, False],
[False, True, True, False]],
fill_value=999999)
>>> np.array(ma[~ma.mask])
array([ 0, 2, 3, 7, 8, 11])
>>> np.ma.notmasked_contiguous(ma)
[slice(0, 1, None), slice(2, 4, None), slice(7, 9, None), slice(11, 12, None)]
>>> np.ma.notmasked_contiguous(ma, axis=0)
[[slice(0, 1, None), slice(2, 3, None)], [], [slice(0, 1, None)], [slice(0, 3, None)]]
>>> np.ma.notmasked_contiguous(ma, axis=1)
[[slice(0, 1, None), slice(2, 4, None)], [slice(3, 4, None)], [slice(0, 1, None), slice(3, 4, None)]]
notmasked_edges(a, axis=None)
Find the indices of the first and last unmasked values along an axis.
If all values are masked, return None. Otherwise, return a list
of two tuples, corresponding to the indices of the first and last
unmasked values respectively.
Parameters
----------
a : array_like
The input array.
axis : int, optional
Axis along which to perform the operation.
If None (default), applies to a flattened version of the array.
Returns
-------
edges : ndarray or list
An array of start and end indexes if there are any masked data in
the array. If there are no masked data in the array, `edges` is a
list of the first and last index.
See Also
--------
flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous
clump_masked, clump_unmasked
Examples
--------
>>> import numpy as np
>>> a = np.arange(9).reshape((3, 3))
>>> m = np.zeros_like(a)
>>> m[1:, 1:] = 1
>>> am = np.ma.array(a, mask=m)
>>> np.array(am[~am.mask])
array([0, 1, 2, 3, 6])
>>> np.ma.notmasked_edges(am)
array([0, 6])
outer(a, b)
Compute the outer product of two vectors.
Given two vectors `a` and `b` of length ``M`` and ``N``, respectively,
the outer product [1]_ is::
[[a_0*b_0 a_0*b_1 ... a_0*b_{N-1} ]
[a_1*b_0 .
[ ... .
[a_{M-1}*b_0 a_{M-1}*b_{N-1} ]]
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
.. versionadded:: 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.
linalg.outer : An Array API compatible variation of ``np.outer``,
which accepts 1-dimensional inputs only.
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:
>>> import numpy as np
>>> 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)
Notes
-----
Masked values are replaced by 0.
outerproduct = outer(a, b)
Compute the outer product of two vectors.
Given two vectors `a` and `b` of length ``M`` and ``N``, respectively,
the outer product [1]_ is::
[[a_0*b_0 a_0*b_1 ... a_0*b_{N-1} ]
[a_1*b_0 .
[ ... .
[a_{M-1}*b_0 a_{M-1}*b_{N-1} ]]
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
.. versionadded:: 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.
linalg.outer : An Array API compatible variation of ``np.outer``,
which accepts 1-dimensional inputs only.
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:
>>> import numpy as np
>>> 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)
Notes
-----
Masked values are replaced by 0.
polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)
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
:doc:`transition guide </reference/routines.polynomials>`.
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 <numpy.polynomial.polynomial.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
----------
x : array_like, shape (M,)
x-coordinates of the M sample points ``(x[i], y[i])``.
y : array_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.
deg : int
Degree of the fitting polynomial
rcond : float, 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.
full : bool, 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.
w : array_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.
cov : bool 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
-------
p : ndarray, 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`.
V : ndarray, shape (deg + 1, deg + 1) or (deg + 1, deg + 1, 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.exceptions.RankWarning)
See Also
--------
polyval : Compute polynomial values.
linalg.lstsq : Computes a least-squares fit.
scipy.interpolate.UnivariateSpline : Computes spline fits.
Notes
-----
Any masked values in x is propagated in y, and vice-versa.
The solution minimizes the squared error
.. math::
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 `~exceptions.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 numpy as np
>>> 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.exceptions.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()
power(a, b, third=None)
Returns element-wise base array raised to power from second array.
This is the masked array version of `numpy.power`. For details see
`numpy.power`.
See Also
--------
numpy.power
Notes
-----
The *out* argument to `numpy.power` is not supported, `third` has to be
None.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = [11.2, -3.973, 0.801, -1.41]
>>> mask = [0, 0, 0, 1]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(data=[11.2, -3.973, 0.801, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.power(masked_x, 2)
masked_array(data=[125.43999999999998, 15.784728999999999,
0.6416010000000001, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> y = [-0.5, 2, 0, 17]
>>> masked_y = ma.masked_array(y, mask)
>>> masked_y
masked_array(data=[-0.5, 2.0, 0.0, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.power(masked_x, masked_y)
masked_array(data=[0.2988071523335984, 15.784728999999999, 1.0, --],
mask=[False, False, False, True],
fill_value=1e+20)
ptp(obj, axis=None, out=None, fill_value=None, keepdims=<no value>)
Return (maximum - minimum) along the given dimension
(i.e. peak-to-peak value).
.. warning::
`ptp` preserves the data type of the array. This means the
return value for an input of signed integers with n bits
(e.g. `np.int8`, `np.int16`, etc) is also a signed integer
with n bits. In that case, peak-to-peak values greater than
``2**(n-1)-1`` will be returned as negative values. An example
with a work-around is shown below.
Parameters
----------
axis : {None, int}, optional
Axis along which to find the peaks. If None (default) the
flattened array is used.
out : {None, array_like}, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
fill_value : scalar or None, optional
Value used to fill in the masked values.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.
Returns
-------
ptp : ndarray.
A new array holding the result, unless ``out`` was
specified, in which case a reference to ``out`` is returned.
Examples
--------
>>> import numpy as np
>>> x = np.ma.MaskedArray([[4, 9, 2, 10],
... [6, 9, 7, 12]])
>>> x.ptp(axis=1)
masked_array(data=[8, 6],
mask=False,
fill_value=999999)
>>> x.ptp(axis=0)
masked_array(data=[2, 0, 5, 2],
mask=False,
fill_value=999999)
>>> x.ptp()
10
This example shows that a negative value can be returned when
the input is an array of signed integers.
>>> y = np.ma.MaskedArray([[1, 127],
... [0, 127],
... [-1, 127],
... [-2, 127]], dtype=np.int8)
>>> y.ptp(axis=1)
masked_array(data=[ 126, 127, -128, -127],
mask=False,
fill_value=np.int64(999999),
dtype=int8)
A work-around is to use the `view()` method to view the result as
unsigned integers with the same bit width:
>>> y.ptp(axis=1).view(np.uint8)
masked_array(data=[126, 127, 128, 129],
mask=False,
fill_value=np.int64(999999),
dtype=uint8)
put(a, indices, values, mode='raise')
Set storage-indexed locations to corresponding values.
This function is equivalent to `MaskedArray.put`, see that method
for details.
See Also
--------
MaskedArray.put
Examples
--------
Putting values in a masked array:
>>> a = np.ma.array([1, 2, 3, 4], mask=[False, True, False, False])
>>> np.ma.put(a, [1, 3], [10, 30])
>>> a
masked_array(data=[ 1, 10, 3, 30],
mask=False,
fill_value=999999)
Using put with a 2D array:
>>> b = np.ma.array([[1, 2], [3, 4]], mask=[[False, True], [False, False]])
>>> np.ma.put(b, [[0, 1], [1, 0]], [[10, 20], [30, 40]])
>>> b
masked_array(
data=[[40, 30],
[ 3, 4]],
mask=False,
fill_value=999999)
putmask(a, mask, values)
Changes elements of an array based on conditional and input values.
This is the masked array version of `numpy.putmask`, for details see
`numpy.putmask`.
See Also
--------
numpy.putmask
Notes
-----
Using a masked array as `values` will **not** transform a `ndarray` into
a `MaskedArray`.
Examples
--------
>>> import numpy as np
>>> arr = [[1, 2], [3, 4]]
>>> mask = [[1, 0], [0, 0]]
>>> x = np.ma.array(arr, mask=mask)
>>> np.ma.putmask(x, x < 4, 10*x)
>>> x
masked_array(
data=[[--, 20],
[30, 4]],
mask=[[ True, False],
[False, False]],
fill_value=999999)
>>> x.data
array([[10, 20],
[30, 4]])
reshape(a, new_shape, order='C')
Returns an array containing the same data with a new shape.
Refer to `MaskedArray.reshape` for full documentation.
See Also
--------
MaskedArray.reshape : equivalent function
Examples
--------
Reshaping a 1-D array:
>>> a = np.ma.array([1, 2, 3, 4])
>>> np.ma.reshape(a, (2, 2))
masked_array(
data=[[1, 2],
[3, 4]],
mask=False,
fill_value=999999)
Reshaping a 2-D array:
>>> b = np.ma.array([[1, 2], [3, 4]])
>>> np.ma.reshape(b, (1, 4))
masked_array(data=[[1, 2, 3, 4]],
mask=False,
fill_value=999999)
Reshaping a 1-D array with a mask:
>>> c = np.ma.array([1, 2, 3, 4], mask=[False, True, False, False])
>>> np.ma.reshape(c, (2, 2))
masked_array(
data=[[1, --],
[3, 4]],
mask=[[False, True],
[False, False]],
fill_value=999999)
resize(x, new_shape)
Return a new masked array with the specified size and shape.
This is the masked equivalent of the `numpy.resize` function. The new
array is filled with repeated copies of `x` (in the order that the
data are stored in memory). If `x` is masked, the new array will be
masked, and the new mask will be a repetition of the old one.
See Also
--------
numpy.resize : Equivalent function in the top level NumPy module.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = ma.array([[1, 2] ,[3, 4]])
>>> a[0, 1] = ma.masked
>>> a
masked_array(
data=[[1, --],
[3, 4]],
mask=[[False, True],
[False, False]],
fill_value=999999)
>>> np.resize(a, (3, 3))
masked_array(
data=[[1, 2, 3],
[4, 1, 2],
[3, 4, 1]],
mask=False,
fill_value=999999)
>>> ma.resize(a, (3, 3))
masked_array(
data=[[1, --, 3],
[4, 1, --],
[3, 4, 1]],
mask=[[False, True, False],
[False, False, True],
[False, False, False]],
fill_value=999999)
A MaskedArray is always returned, regardless of the input type.
>>> a = np.array([[1, 2] ,[3, 4]])
>>> ma.resize(a, (3, 3))
masked_array(
data=[[1, 2, 3],
[4, 1, 2],
[3, 4, 1]],
mask=False,
fill_value=999999)
right_shift(a, n)
Shift the bits of an integer to the right.
This is the masked array version of `numpy.right_shift`, for details
see that function.
See Also
--------
numpy.right_shift
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = [11, 3, 8, 1]
>>> mask = [0, 0, 0, 1]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(data=[11, 3, 8, --],
mask=[False, False, False, True],
fill_value=999999)
>>> ma.right_shift(masked_x,1)
masked_array(data=[5, 1, 4, --],
mask=[False, False, False, True],
fill_value=999999)
round = round_(a, decimals=0, out=None)
Return a copy of a, rounded to 'decimals' places.
When 'decimals' is negative, it specifies the number of positions
to the left of the decimal point. The real and imaginary parts of
complex numbers are rounded separately. Nothing is done if the
array is not of float type and 'decimals' is greater than or equal
to 0.
Parameters
----------
decimals : int
Number of decimals to round to. May be negative.
out : array_like
Existing array to use for output.
If not given, returns a default copy of a.
Notes
-----
If out is given and does not have a mask attribute, the mask of a
is lost!
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = [11.2, -3.973, 0.801, -1.41]
>>> mask = [0, 0, 0, 1]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(data=[11.2, -3.973, 0.801, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round_(masked_x)
masked_array(data=[11.0, -4.0, 1.0, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round(masked_x, decimals=1)
masked_array(data=[11.2, -4.0, 0.8, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round_(masked_x, decimals=-1)
masked_array(data=[10.0, -0.0, 0.0, --],
mask=[False, False, False, True],
fill_value=1e+20)
round_(a, decimals=0, out=None)
Return a copy of a, rounded to 'decimals' places.
When 'decimals' is negative, it specifies the number of positions
to the left of the decimal point. The real and imaginary parts of
complex numbers are rounded separately. Nothing is done if the
array is not of float type and 'decimals' is greater than or equal
to 0.
Parameters
----------
decimals : int
Number of decimals to round to. May be negative.
out : array_like
Existing array to use for output.
If not given, returns a default copy of a.
Notes
-----
If out is given and does not have a mask attribute, the mask of a
is lost!
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = [11.2, -3.973, 0.801, -1.41]
>>> mask = [0, 0, 0, 1]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(data=[11.2, -3.973, 0.801, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round_(masked_x)
masked_array(data=[11.0, -4.0, 1.0, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round(masked_x, decimals=1)
masked_array(data=[11.2, -4.0, 0.8, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.round_(masked_x, decimals=-1)
masked_array(data=[10.0, -0.0, 0.0, --],
mask=[False, False, False, True],
fill_value=1e+20)
set_fill_value(a, fill_value)
Set the filling value of a, if a is a masked array.
This function changes the fill value of the masked array `a` in place.
If `a` is not a masked array, the function returns silently, without
doing anything.
Parameters
----------
a : array_like
Input array.
fill_value : dtype
Filling value. A consistency test is performed to make sure
the value is compatible with the dtype of `a`.
Returns
-------
None
Nothing returned by this function.
See Also
--------
maximum_fill_value : Return the default fill value for a dtype.
MaskedArray.fill_value : Return current fill value.
MaskedArray.set_fill_value : Equivalent method.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> a = ma.masked_where(a < 3, a)
>>> a
masked_array(data=[--, --, --, 3, 4],
mask=[ True, True, True, False, False],
fill_value=999999)
>>> ma.set_fill_value(a, -999)
>>> a
masked_array(data=[--, --, --, 3, 4],
mask=[ True, True, True, False, False],
fill_value=-999)
Nothing happens if `a` is not a masked array.
>>> a = list(range(5))
>>> a
[0, 1, 2, 3, 4]
>>> ma.set_fill_value(a, 100)
>>> a
[0, 1, 2, 3, 4]
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> ma.set_fill_value(a, 100)
>>> a
array([0, 1, 2, 3, 4])
setdiff1d(ar1, ar2, assume_unique=False)
Set difference of 1D arrays with unique elements.
The output is always a masked array. See `numpy.setdiff1d` for more
details.
See Also
--------
numpy.setdiff1d : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 1])
>>> np.ma.setdiff1d(x, [1, 2])
masked_array(data=[3, --],
mask=[False, True],
fill_value=999999)
setxor1d(ar1, ar2, assume_unique=False)
Set exclusive-or of 1-D arrays with unique elements.
The output is always a masked array. See `numpy.setxor1d` for more details.
See Also
--------
numpy.setxor1d : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> ar1 = np.ma.array([1, 2, 3, 2, 4])
>>> ar2 = np.ma.array([2, 3, 5, 7, 5])
>>> np.ma.setxor1d(ar1, ar2)
masked_array(data=[1, 4, 5, 7],
mask=False,
fill_value=999999)
shape(obj)
Return the shape of an array.
Parameters
----------
a : array_like
Input array.
Returns
-------
shape : tuple of ints
The elements of the shape tuple give the lengths of the
corresponding array dimensions.
See Also
--------
len : ``len(a)`` is equivalent to ``np.shape(a)[0]`` for N-D arrays with
``N>=1``.
ndarray.shape : Equivalent array method.
Examples
--------
>>> import numpy as np
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 3]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
>>> a = np.array([(1, 2), (3, 4), (5, 6)],
... dtype=[('x', 'i4'), ('y', 'i4')])
>>> np.shape(a)
(3,)
>>> a.shape
(3,)
size(obj, axis=None)
Return the number of elements along a given axis.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which the elements are counted. By default, give
the total number of elements.
Returns
-------
element_count : int
Number of elements along the specified axis.
See Also
--------
shape : dimensions of array
ndarray.shape : dimensions of array
ndarray.size : number of elements in array
Examples
--------
>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
sometrue = reduce(target, axis=0, dtype=None) method of numpy.ma.core._MaskedBinaryOperation instance
Reduce `target` along the given `axis`.
sort(a, axis=-1, kind=None, order=None, endwith=True, fill_value=None, *, stable=None)
Return a sorted copy of the masked array.
Equivalent to creating a copy of the array
and applying the MaskedArray ``sort()`` method.
Refer to ``MaskedArray.sort`` for the full documentation
See Also
--------
MaskedArray.sort : equivalent method
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = [11.2, -3.973, 0.801, -1.41]
>>> mask = [0, 0, 0, 1]
>>> masked_x = ma.masked_array(x, mask)
>>> masked_x
masked_array(data=[11.2, -3.973, 0.801, --],
mask=[False, False, False, True],
fill_value=1e+20)
>>> ma.sort(masked_x)
masked_array(data=[-3.973, 0.801, 11.2, --],
mask=[False, False, False, True],
fill_value=1e+20)
take(a, indices, axis=None, out=None, mode='raise')
transpose(a, axes=None)
Permute the dimensions of an array.
This function is exactly equivalent to `numpy.transpose`.
See Also
--------
numpy.transpose : Equivalent function in top-level NumPy module.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = ma.arange(4).reshape((2,2))
>>> x[1, 1] = ma.masked
>>> x
masked_array(
data=[[0, 1],
[2, --]],
mask=[[False, False],
[False, True]],
fill_value=999999)
>>> ma.transpose(x)
masked_array(
data=[[0, 2],
[1, --]],
mask=[[False, False],
[False, True]],
fill_value=999999)
union1d(ar1, ar2)
Union of two arrays.
The output is always a masked array. See `numpy.union1d` for more details.
See Also
--------
numpy.union1d : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> ar1 = np.ma.array([1, 2, 3, 4])
>>> ar2 = np.ma.array([3, 4, 5, 6])
>>> np.ma.union1d(ar1, ar2)
masked_array(data=[1, 2, 3, 4, 5, 6],
mask=False,
fill_value=999999)
unique(ar1, return_index=False, return_inverse=False)
Finds the unique elements of an array.
Masked values are considered the same element (masked). The output array
is always a masked array. See `numpy.unique` for more details.
See Also
--------
numpy.unique : Equivalent function for ndarrays.
Examples
--------
>>> import numpy as np
>>> a = [1, 2, 1000, 2, 3]
>>> mask = [0, 0, 1, 0, 0]
>>> masked_a = np.ma.masked_array(a, mask)
>>> masked_a
masked_array(data=[1, 2, --, 2, 3],
mask=[False, False, True, False, False],
fill_value=999999)
>>> np.ma.unique(masked_a)
masked_array(data=[1, 2, 3, --],
mask=[False, False, False, True],
fill_value=999999)
>>> np.ma.unique(masked_a, return_index=True)
(masked_array(data=[1, 2, 3, --],
mask=[False, False, False, True],
fill_value=999999), array([0, 1, 4, 2]))
>>> np.ma.unique(masked_a, return_inverse=True)
(masked_array(data=[1, 2, 3, --],
mask=[False, False, False, True],
fill_value=999999), array([0, 1, 3, 1, 2]))
>>> np.ma.unique(masked_a, return_index=True, return_inverse=True)
(masked_array(data=[1, 2, 3, --],
mask=[False, False, False, True],
fill_value=999999), array([0, 1, 4, 2]), array([0, 1, 3, 1, 2]))
vander(x, n=None)
Generate a Vandermonde matrix.
The columns of the output matrix are powers of the input vector. The
order of the powers is determined by the `increasing` boolean argument.
Specifically, when `increasing` is False, the `i`-th output column is
the input vector raised element-wise to the power of ``N - i - 1``. Such
a matrix with a geometric progression in each row is named for Alexandre-
Theophile Vandermonde.
Parameters
----------
x : array_like
1-D input array.
N : int, optional
Number of columns in the output. If `N` is not specified, a square
array is returned (``N = len(x)``).
increasing : bool, optional
Order of the powers of the columns. If True, the powers increase
from left to right, if False (the default) they are reversed.
.. versionadded:: 1.9.0
Returns
-------
out : ndarray
Vandermonde matrix. If `increasing` is False, the first column is
``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is
True, the columns are ``x^0, x^1, ..., x^(N-1)``.
See Also
--------
polynomial.polynomial.polyvander
Examples
--------
>>> import numpy as np
>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> np.column_stack([x**(N-1-i) for i in range(N)])
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> x = np.array([1, 2, 3, 5])
>>> np.vander(x)
array([[ 1, 1, 1, 1],
[ 8, 4, 2, 1],
[ 27, 9, 3, 1],
[125, 25, 5, 1]])
>>> np.vander(x, increasing=True)
array([[ 1, 1, 1, 1],
[ 1, 2, 4, 8],
[ 1, 3, 9, 27],
[ 1, 5, 25, 125]])
The determinant of a square Vandermonde matrix is the product
of the differences between the values of the input vector:
>>> np.linalg.det(np.vander(x))
48.000000000000043 # may vary
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48
Notes
-----
Masked values in the input array result in rows of zeros.
where(condition, x=<no value>, y=<no value>)
Return a masked array with elements from `x` or `y`, depending on condition.
.. note::
When only `condition` is provided, this function is identical to
`nonzero`. The rest of this documentation covers only the case where
all three arguments are provided.
Parameters
----------
condition : array_like, bool
Where True, yield `x`, otherwise yield `y`.
x, y : array_like, optional
Values from which to choose. `x`, `y` and `condition` need to be
broadcastable to some shape.
Returns
-------
out : MaskedArray
An masked array with `masked` elements where the condition is masked,
elements from `x` where `condition` is True, and elements from `y`
elsewhere.
See Also
--------
numpy.where : Equivalent function in the top-level NumPy module.
nonzero : The function that is called when x and y are omitted
Examples
--------
>>> import numpy as np
>>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0],
... [1, 0, 1],
... [0, 1, 0]])
>>> x
masked_array(
data=[[0.0, --, 2.0],
[--, 4.0, --],
[6.0, --, 8.0]],
mask=[[False, True, False],
[ True, False, True],
[False, True, False]],
fill_value=1e+20)
>>> np.ma.where(x > 5, x, -3.1416)
masked_array(
data=[[-3.1416, --, -3.1416],
[--, -3.1416, --],
[6.0, --, 8.0]],
mask=[[False, True, False],
[ True, False, True],
[False, True, False]],
fill_value=1e+20)
DATA
__all__ = ['core', 'extras', 'MAError', 'MaskError', 'MaskType', 'Mask...
abs = <numpy.ma.core._MaskedUnaryOperation object>
absolute(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Calculate the absolute value element-wise.
``np.abs`` is a shorthand for this function.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
absolute : ndarray
An ndarray containing the absolute value of
each element in `x`. For complex input, ``a + ib``, the
absolute value is :math:`\sqrt{ a^2 + b^2 }`.
This is a scalar if `x` is a scalar.
Examples
--------
>>> import numpy as np
>>> x = np.array([-1.2, 1.2])
>>> np.absolute(x)
array([ 1.2, 1.2])
>>> np.absolute(1.2 + 1j)
1.5620499351813308
Plot the function over ``[-10, 10]``:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(start=-10, stop=10, num=101)
>>> plt.plot(x, np.absolute(x))
>>> plt.show()
Plot the function over the complex plane:
>>> xx = x + 1j * x[:, np.newaxis]
>>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray')
>>> plt.show()
The `abs` function can be used as a shorthand for ``np.absolute`` on
ndarrays.
>>> x = np.array([-1.2, 1.2])
>>> abs(x)
array([1.2, 1.2])
absolute = <numpy.ma.core._MaskedUnaryOperation object>
absolute(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Calculate the absolute value element-wise.
``np.abs`` is a shorthand for this function.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
absolute : ndarray
An ndarray containing the absolute value of
each element in `x`. For complex input, ``a + ib``, the
absolute value is :math:`\sqrt{ a^2 + b^2 }`.
This is a scalar if `x` is a scalar.
Examples
--------
>>> import numpy as np
>>> x = np.array([-1.2, 1.2])
>>> np.absolute(x)
array([ 1.2, 1.2])
>>> np.absolute(1.2 + 1j)
1.5620499351813308
Plot the function over ``[-10, 10]``:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(start=-10, stop=10, num=101)
>>> plt.plot(x, np.absolute(x))
>>> plt.show()
Plot the function over the complex plane:
>>> xx = x + 1j * x[:, np.newaxis]
>>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray')
>>> plt.show()
The `abs` function can be used as a shorthand for ``np.absolute`` on
ndarrays.
>>> x = np.array([-1.2, 1.2])
>>> abs(x)
array([1.2, 1.2])
add = <numpy.ma.core._MaskedBinaryOperation object>
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
add : ndarray or scalar
The sum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.
Examples
--------
>>> import numpy as np
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
The ``+`` operator can be used as a shorthand for ``np.add`` on ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 + x2
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
all = <numpy.ma.core._frommethod object>
all(self, axis=None, out=None, keepdims=<no value>)
Returns True if all elements evaluate to True.
The output array is masked where all the values along the given axis
are masked: if the output would have been a scalar and that all the
values are masked, then the output is `masked`.
Refer to `numpy.all` for full documentation.
See Also
--------
numpy.ndarray.all : corresponding function for ndarrays
numpy.all : equivalent function
Examples
--------
>>> import numpy as np
>>> np.ma.array([1,2,3]).all()
True
>>> a = np.ma.array([1,2,3], mask=True)
>>> (a.all() is np.ma.masked)
True
angle = <numpy.ma.core._MaskedUnaryOperation object>
Return the angle of the complex argument.
Parameters
----------
z : array_like
A complex number or sequence of complex numbers.
deg : bool, optional
Return angle in degrees if True, radians if False (default).
Returns
-------
angle : ndarray or scalar
The counterclockwise angle from the positive real axis on the complex
plane in the range ``(-pi, pi]``, with dtype as numpy.float64.
.. versionchanged:: 1.16.0
This function works on subclasses of ndarray like `ma.array`.
See Also
--------
arctan2
absolute
Notes
-----
This function passes the imaginary and real parts of the argument to
`arctan2` to compute the result; consequently, it follows the convention
of `arctan2` when the magnitude of the argument is zero. See example.
Examples
--------
>>> import numpy as np
>>> np.angle([1.0, 1.0j, 1+1j]) # in radians
array([ 0. , 1.57079633, 0.78539816]) # may vary
>>> np.angle(1+1j, deg=True) # in degrees
45.0
>>> np.angle([0., -0., complex(0., -0.), complex(-0., -0.)]) # convention
array([ 0. , 3.14159265, -0. , -3.14159265])
anom = <numpy.ma.core._frommethod object>
anom(self, axis=None, dtype=None)
Compute the anomalies (deviations from the arithmetic mean)
along the given axis.
Returns an array of anomalies, with the same shape as the input and
where the arithmetic mean is computed along the given axis.
Parameters
----------
axis : int, optional
Axis over which the anomalies are taken.
The default is to use the mean of the flattened array as reference.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as
the array type.
See Also
--------
mean : Compute the mean of the array.
Examples
--------
>>> import numpy as np
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data=[-1., 0., 1.],
mask=False,
fill_value=1e+20)
anomalies = <numpy.ma.core._frommethod object>
anom(self, axis=None, dtype=None)
Compute the anomalies (deviations from the arithmetic mean)
along the given axis.
Returns an array of anomalies, with the same shape as the input and
where the arithmetic mean is computed along the given axis.
Parameters
----------
axis : int, optional
Axis over which the anomalies are taken.
The default is to use the mean of the flattened array as reference.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as
the array type.
See Also
--------
mean : Compute the mean of the array.
Examples
--------
>>> import numpy as np
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data=[-1., 0., 1.],
mask=False,
fill_value=1e+20)
any = <numpy.ma.core._frommethod object>
any(self, axis=None, out=None, keepdims=<no value>)
Returns True if any of the elements of `a` evaluate to True.
Masked values are considered as False during computation.
Refer to `numpy.any` for full documentation.
See Also
--------
numpy.ndarray.any : corresponding function for ndarrays
numpy.any : equivalent function
arange = <numpy.ma.core._convert2ma object>
arange([start,] stop[, step,], dtype=None, *, device=None, like=None)
Return evenly spaced values within a given interval.
``arange`` can be called with a varying number of positional arguments:
* ``arange(stop)``: Values are generated within the half-open interval
``[0, stop)`` (in other words, the interval including `start` but
excluding `stop`).
* ``arange(start, stop)``: Values are generated within the half-open
interval ``[start, stop)``.
* ``arange(start, stop, step)`` Values are generated within the half-open
interval ``[start, stop)``, with spacing between values given by
``step``.
For integer arguments the function is roughly equivalent to the Python
built-in :py:class:`range`, but returns an ndarray rather than a ``range``
instance.
When using a non-integer step, such as 0.1, it is often better to use
`numpy.linspace`.
See the Warning sections below for more information.
Parameters
----------
start : integer or real, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : integer or real
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : integer or real, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
dtype : dtype, optional
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
device : str, optional
The device on which to place the created array. Default: ``None``.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
arange : MaskedArray
Array of evenly spaced values.
For floating point arguments, the length of the result is
``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.
Warnings
--------
The length of the output might not be numerically stable.
Another stability issue is due to the internal implementation of
`numpy.arange`.
The actual step value used to populate the array is
``dtype(start + step) - dtype(start)`` and not `step`. Precision loss
can occur here, due to casting or due to using floating points when
`start` is much larger than `step`. This can lead to unexpected
behaviour. For example::
>>> np.arange(0, 5, 0.5, dtype=int)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> np.arange(-3, 3, 0.5, dtype=int)
array([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
In such cases, the use of `numpy.linspace` should be preferred.
The built-in :py:class:`range` generates :std:doc:`Python built-in integers
that have arbitrary size <python:c-api/long>`, while `numpy.arange`
produces `numpy.int32` or `numpy.int64` numbers. This may result in
incorrect results for large integer values::
>>> power = 40
>>> modulo = 10000
>>> x1 = [(n ** power) % modulo for n in range(8)]
>>> x2 = [(n ** power) % modulo for n in np.arange(8)]
>>> print(x1)
[0, 1, 7776, 8801, 6176, 625, 6576, 4001] # correct
>>> print(x2)
[0, 1, 7776, 7185, 0, 5969, 4816, 3361] # incorrect
See Also
--------
numpy.linspace : Evenly spaced numbers with careful handling of endpoints.
numpy.ogrid: Arrays of evenly spaced numbers in N-dimensions.
numpy.mgrid: Grid-shaped arrays of evenly spaced numbers in N-dimensions.
:ref:`how-to-partition`
Examples
--------
>>> import numpy as np
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
arccos = <numpy.ma.core._MaskedUnaryOperation object>
arccos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Trigonometric inverse cosine, element-wise.
The inverse of `cos` so that, if ``y = cos(x)``, then ``x = arccos(y)``.
Parameters
----------
x : array_like
`x`-coordinate on the unit circle.
For real arguments, the domain is [-1, 1].
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
angle : ndarray
The angle of the ray intersecting the unit circle at the given
`x`-coordinate in radians [0, pi].
This is a scalar if `x` is a scalar.
See Also
--------
cos, arctan, arcsin, emath.arccos
Notes
-----
`arccos` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that ``cos(z) = x``. The convention is to return
the angle `z` whose real part lies in `[0, pi]`.
For real-valued input data types, `arccos` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arccos` is a complex analytic function that
has branch cuts ``[-inf, -1]`` and `[1, inf]` and is continuous from
above on the former and from below on the latter.
The inverse `cos` is also known as `acos` or cos^-1.
References
----------
M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 79.
https://personal.math.ubc.ca/~cbm/aands/page_79.htm
Examples
--------
>>> import numpy as np
We expect the arccos of 1 to be 0, and of -1 to be pi:
>>> np.arccos([1, -1])
array([ 0. , 3.14159265])
Plot arccos:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-1, 1, num=100)
>>> plt.plot(x, np.arccos(x))
>>> plt.axis('tight')
>>> plt.show()
arccosh = <numpy.ma.core._MaskedUnaryOperation object>
arccosh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse hyperbolic cosine, element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
arccosh : ndarray
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
See Also
--------
cosh, arcsinh, sinh, arctanh, tanh
Notes
-----
`arccosh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `cosh(z) = x`. The convention is to return the
`z` whose imaginary part lies in ``[-pi, pi]`` and the real part in
``[0, inf]``.
For real-valued input data types, `arccosh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arccosh` is a complex analytical function that
has a branch cut `[-inf, 1]` and is continuous from above on it.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86.
https://personal.math.ubc.ca/~cbm/aands/page_86.htm
.. [2] Wikipedia, "Inverse hyperbolic function",
https://en.wikipedia.org/wiki/Arccosh
Examples
--------
>>> import numpy as np
>>> np.arccosh([np.e, 10.0])
array([ 1.65745445, 2.99322285])
>>> np.arccosh(1)
0.0
arcsin = <numpy.ma.core._MaskedUnaryOperation object>
arcsin(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse sine, element-wise.
Parameters
----------
x : array_like
`y`-coordinate on the unit circle.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
angle : ndarray
The inverse sine of each element in `x`, in radians and in the
closed interval ``[-pi/2, pi/2]``.
This is a scalar if `x` is a scalar.
See Also
--------
sin, cos, arccos, tan, arctan, arctan2, emath.arcsin
Notes
-----
`arcsin` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that :math:`sin(z) = x`. The convention is to
return the angle `z` whose real part lies in [-pi/2, pi/2].
For real-valued input data types, *arcsin* always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arcsin` is a complex analytic function that
has, by convention, the branch cuts [-inf, -1] and [1, inf] and is
continuous from above on the former and from below on the latter.
The inverse sine is also known as `asin` or sin^{-1}.
References
----------
Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*,
10th printing, New York: Dover, 1964, pp. 79ff.
https://personal.math.ubc.ca/~cbm/aands/page_79.htm
Examples
--------
>>> import numpy as np
>>> np.arcsin(1) # pi/2
1.5707963267948966
>>> np.arcsin(-1) # -pi/2
-1.5707963267948966
>>> np.arcsin(0)
0.0
arcsinh = <numpy.ma.core._MaskedUnaryOperation object>
arcsinh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse hyperbolic sine element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
Notes
-----
`arcsinh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that `sinh(z) = x`. The convention is to return the
`z` whose imaginary part lies in `[-pi/2, pi/2]`.
For real-valued input data types, `arcsinh` always returns real output.
For each value that cannot be expressed as a real number or infinity, it
returns ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arcsinh` is a complex analytical function that
has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from
the right on the former and from the left on the latter.
The inverse hyperbolic sine is also known as `asinh` or ``sinh^-1``.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86.
https://personal.math.ubc.ca/~cbm/aands/page_86.htm
.. [2] Wikipedia, "Inverse hyperbolic function",
https://en.wikipedia.org/wiki/Arcsinh
Examples
--------
>>> import numpy as np
>>> np.arcsinh(np.array([np.e, 10.0]))
array([ 1.72538256, 2.99822295])
arctan = <numpy.ma.core._MaskedUnaryOperation object>
arctan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Trigonometric inverse tangent, element-wise.
The inverse of tan, so that if ``y = tan(x)`` then ``x = arctan(y)``.
Parameters
----------
x : array_like
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Out has the same shape as `x`. Its real part is in
``[-pi/2, pi/2]`` (``arctan(+/-inf)`` returns ``+/-pi/2``).
This is a scalar if `x` is a scalar.
See Also
--------
arctan2 : The "four quadrant" arctan of the angle formed by (`x`, `y`)
and the positive `x`-axis.
angle : Argument of complex values.
Notes
-----
`arctan` is a multi-valued function: for each `x` there are infinitely
many numbers `z` such that tan(`z`) = `x`. The convention is to return
the angle `z` whose real part lies in [-pi/2, pi/2].
For real-valued input data types, `arctan` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arctan` is a complex analytic function that
has [``1j, infj``] and [``-1j, -infj``] as branch cuts, and is continuous
from the left on the former and from the right on the latter.
The inverse tangent is also known as `atan` or tan^{-1}.
References
----------
Abramowitz, M. and Stegun, I. A., *Handbook of Mathematical Functions*,
10th printing, New York: Dover, 1964, pp. 79.
https://personal.math.ubc.ca/~cbm/aands/page_79.htm
Examples
--------
We expect the arctan of 0 to be 0, and of 1 to be pi/4:
>>> import numpy as np
>>> np.arctan([0, 1])
array([ 0. , 0.78539816])
>>> np.pi/4
0.78539816339744828
Plot arctan:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-10, 10)
>>> plt.plot(x, np.arctan(x))
>>> plt.axis('tight')
>>> plt.show()
arctan2 = <numpy.ma.core._MaskedBinaryOperation object>
arctan2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Element-wise arc tangent of ``x1/x2`` choosing the quadrant correctly.
The quadrant (i.e., branch) is chosen so that ``arctan2(x1, x2)`` is
the signed angle in radians between the ray ending at the origin and
passing through the point (1,0), and the ray ending at the origin and
passing through the point (`x2`, `x1`). (Note the role reversal: the
"`y`-coordinate" is the first function parameter, the "`x`-coordinate"
is the second.) By IEEE convention, this function is defined for
`x2` = +/-0 and for either or both of `x1` and `x2` = +/-inf (see
Notes for specific values).
This function is not defined for complex-valued arguments; for the
so-called argument of complex values, use `angle`.
Parameters
----------
x1 : array_like, real-valued
`y`-coordinates.
x2 : array_like, real-valued
`x`-coordinates.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
angle : ndarray
Array of angles in radians, in the range ``[-pi, pi]``.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
arctan, tan, angle
Notes
-----
*arctan2* is identical to the `atan2` function of the underlying
C library. The following special values are defined in the C
standard: [1]_
====== ====== ================
`x1` `x2` `arctan2(x1,x2)`
====== ====== ================
+/- 0 +0 +/- 0
+/- 0 -0 +/- pi
> 0 +/-inf +0 / +pi
< 0 +/-inf -0 / -pi
+/-inf +inf +/- (pi/4)
+/-inf -inf +/- (3*pi/4)
====== ====== ================
Note that +0 and -0 are distinct floating point numbers, as are +inf
and -inf.
References
----------
.. [1] ISO/IEC standard 9899:1999, "Programming language C."
Examples
--------
Consider four points in different quadrants:
>>> import numpy as np
>>> x = np.array([-1, +1, +1, -1])
>>> y = np.array([-1, -1, +1, +1])
>>> np.arctan2(y, x) * 180 / np.pi
array([-135., -45., 45., 135.])
Note the order of the parameters. `arctan2` is defined also when `x2` = 0
and at several other special points, obtaining values in
the range ``[-pi, pi]``:
>>> np.arctan2([1., -1.], [0., 0.])
array([ 1.57079633, -1.57079633])
>>> np.arctan2([0., 0., np.inf], [+0., -0., np.inf])
array([0. , 3.14159265, 0.78539816])
arctanh = <numpy.ma.core._MaskedUnaryOperation object>
arctanh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Inverse hyperbolic tangent element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Array of the same shape as `x`.
This is a scalar if `x` is a scalar.
See Also
--------
emath.arctanh
Notes
-----
`arctanh` is a multivalued function: for each `x` there are infinitely
many numbers `z` such that ``tanh(z) = x``. The convention is to return
the `z` whose imaginary part lies in `[-pi/2, pi/2]`.
For real-valued input data types, `arctanh` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `arctanh` is a complex analytical function
that has branch cuts `[-1, -inf]` and `[1, inf]` and is continuous from
above on the former and from below on the latter.
The inverse hyperbolic tangent is also known as `atanh` or ``tanh^-1``.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 86.
https://personal.math.ubc.ca/~cbm/aands/page_86.htm
.. [2] Wikipedia, "Inverse hyperbolic function",
https://en.wikipedia.org/wiki/Arctanh
Examples
--------
>>> import numpy as np
>>> np.arctanh([0, -0.5])
array([ 0. , -0.54930614])
argmax = <numpy.ma.core._frommethod object>
argmax(self, axis=None, fill_value=None, out=None)
Returns array of indices of the maximum values along the given axis.
Masked values are treated as if they had the value fill_value.
Parameters
----------
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis
fill_value : scalar or None, optional
Value used to fill in the masked values. If None, the output of
maximum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
Returns
-------
index_array : {integer_array}
Examples
--------
>>> import numpy as np
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])
argmin = <numpy.ma.core._frommethod object>
argmin(self, axis=None, fill_value=None, out=None)
Return array of indices to the minimum values along the given axis.
Parameters
----------
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis
fill_value : scalar or None, optional
Value used to fill in the masked values. If None, the output of
minimum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
Returns
-------
ndarray or scalar
If multi-dimension input, returns a new ndarray of indices to the
minimum values along the given axis. Otherwise, returns a scalar
of index to the minimum values along the given axis.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array(np.arange(4), mask=[1,1,0,0])
>>> x.shape = (2,2)
>>> x
masked_array(
data=[[--, --],
[2, 3]],
mask=[[ True, True],
[False, False]],
fill_value=999999)
>>> x.argmin(axis=0, fill_value=-1)
array([0, 0])
>>> x.argmin(axis=0, fill_value=9)
array([1, 1])
around = <numpy.ma.core._MaskedUnaryOperation object>
Round an array to the given number of decimals.
`around` is an alias of `~numpy.round`.
See Also
--------
ndarray.round : equivalent method
round : alias for this function
ceil, fix, floor, rint, trunc
atleast_1d = <numpy.ma.extras._fromnxfunction_allargs object>
Convert inputs to arrays with at least one dimension.
Scalar inputs are converted to 1-dimensional arrays, whilst
higher-dimensional inputs are preserved.
Parameters
----------
arys1, arys2, ... : array_like
One or more input arrays.
Returns
-------
ret : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 1``.
Copies are made only if necessary.
See Also
--------
atleast_2d, atleast_3d
Examples
--------
>>> import numpy as np
>>> np.atleast_1d(1.0)
array([1.])
>>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array([[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]])
>>> np.atleast_1d(x) is x
True
>>> np.atleast_1d(1, [3, 4])
(array([1]), array([3, 4]))
Notes
-----
The function is applied to both the _data and the _mask, if any.
atleast_2d = <numpy.ma.extras._fromnxfunction_allargs object>
View inputs as arrays with at least two dimensions.
Parameters
----------
arys1, arys2, ... : array_like
One or more array-like sequences. Non-array inputs are converted
to arrays. Arrays that already have two or more dimensions are
preserved.
Returns
-------
res, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 2``.
Copies are avoided where possible, and views with two or more
dimensions are returned.
See Also
--------
atleast_1d, atleast_3d
Examples
--------
>>> import numpy as np
>>> np.atleast_2d(3.0)
array([[3.]])
>>> x = np.arange(3.0)
>>> np.atleast_2d(x)
array([[0., 1., 2.]])
>>> np.atleast_2d(x).base is x
True
>>> np.atleast_2d(1, [1, 2], [[1, 2]])
(array([[1]]), array([[1, 2]]), array([[1, 2]]))
Notes
-----
The function is applied to both the _data and the _mask, if any.
atleast_3d = <numpy.ma.extras._fromnxfunction_allargs object>
View inputs as arrays with at least three dimensions.
Parameters
----------
arys1, arys2, ... : array_like
One or more array-like sequences. Non-array inputs are converted to
arrays. Arrays that already have three or more dimensions are
preserved.
Returns
-------
res1, res2, ... : ndarray
An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are
avoided where possible, and views with three or more dimensions are
returned. For example, a 1-D array of shape ``(N,)`` becomes a view
of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a
view of shape ``(M, N, 1)``.
See Also
--------
atleast_1d, atleast_2d
Examples
--------
>>> import numpy as np
>>> np.atleast_3d(3.0)
array([[[3.]]])
>>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)
>>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> np.atleast_3d(x).base is x.base # x is a reshape, so not base itself
True
>>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]):
... print(arr, arr.shape) # doctest: +SKIP
...
[[[1]
[2]]] (1, 2, 1)
[[[1]
[2]]] (1, 2, 1)
[[[1 2]]] (1, 1, 2)
Notes
-----
The function is applied to both the _data and the _mask, if any.
bitwise_and = <numpy.ma.core._MaskedBinaryOperation object>
bitwise_and(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the bit-wise AND of two arrays element-wise.
Computes the bit-wise AND of the underlying binary representation of
the integers in the input arrays. This ufunc implements the C/Python
operator ``&``.
Parameters
----------
x1, x2 : array_like
Only integer and boolean types are handled.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Result.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_and
bitwise_or
bitwise_xor
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
>>> import numpy as np
The number 13 is represented by ``00001101``. Likewise, 17 is
represented by ``00010001``. The bit-wise AND of 13 and 17 is
therefore ``000000001``, or 1:
>>> np.bitwise_and(13, 17)
1
>>> np.bitwise_and(14, 13)
12
>>> np.binary_repr(12)
'1100'
>>> np.bitwise_and([14,3], 13)
array([12, 1])
>>> np.bitwise_and([11,7], [4,25])
array([0, 1])
>>> np.bitwise_and(np.array([2,5,255]), np.array([3,14,16]))
array([ 2, 4, 16])
>>> np.bitwise_and([True, True], [False, True])
array([False, True])
The ``&`` operator can be used as a shorthand for ``np.bitwise_and`` on
ndarrays.
>>> x1 = np.array([2, 5, 255])
>>> x2 = np.array([3, 14, 16])
>>> x1 & x2
array([ 2, 4, 16])
bitwise_or = <numpy.ma.core._MaskedBinaryOperation object>
bitwise_or(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the bit-wise OR of two arrays element-wise.
Computes the bit-wise OR of the underlying binary representation of
the integers in the input arrays. This ufunc implements the C/Python
operator ``|``.
Parameters
----------
x1, x2 : array_like
Only integer and boolean types are handled.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Result.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_or
bitwise_and
bitwise_xor
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
>>> import numpy as np
The number 13 has the binary representation ``00001101``. Likewise,
16 is represented by ``00010000``. The bit-wise OR of 13 and 16 is
then ``00011101``, or 29:
>>> np.bitwise_or(13, 16)
29
>>> np.binary_repr(29)
'11101'
>>> np.bitwise_or(32, 2)
34
>>> np.bitwise_or([33, 4], 1)
array([33, 5])
>>> np.bitwise_or([33, 4], [1, 2])
array([33, 6])
>>> np.bitwise_or(np.array([2, 5, 255]), np.array([4, 4, 4]))
array([ 6, 5, 255])
>>> np.array([2, 5, 255]) | np.array([4, 4, 4])
array([ 6, 5, 255])
>>> np.bitwise_or(np.array([2, 5, 255, 2147483647], dtype=np.int32),
... np.array([4, 4, 4, 2147483647], dtype=np.int32))
array([ 6, 5, 255, 2147483647])
>>> np.bitwise_or([True, True], [False, True])
array([ True, True])
The ``|`` operator can be used as a shorthand for ``np.bitwise_or`` on
ndarrays.
>>> x1 = np.array([2, 5, 255])
>>> x2 = np.array([4, 4, 4])
>>> x1 | x2
array([ 6, 5, 255])
bitwise_xor = <numpy.ma.core._MaskedBinaryOperation object>
bitwise_xor(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the bit-wise XOR of two arrays element-wise.
Computes the bit-wise XOR of the underlying binary representation of
the integers in the input arrays. This ufunc implements the C/Python
operator ``^``.
Parameters
----------
x1, x2 : array_like
Only integer and boolean types are handled.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Result.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_xor
bitwise_and
bitwise_or
binary_repr :
Return the binary representation of the input number as a string.
Examples
--------
>>> import numpy as np
The number 13 is represented by ``00001101``. Likewise, 17 is
represented by ``00010001``. The bit-wise XOR of 13 and 17 is
therefore ``00011100``, or 28:
>>> np.bitwise_xor(13, 17)
28
>>> np.binary_repr(28)
'11100'
>>> np.bitwise_xor(31, 5)
26
>>> np.bitwise_xor([31,3], 5)
array([26, 6])
>>> np.bitwise_xor([31,3], [5,6])
array([26, 5])
>>> np.bitwise_xor([True, True], [False, True])
array([ True, False])
The ``^`` operator can be used as a shorthand for ``np.bitwise_xor`` on
ndarrays.
>>> x1 = np.array([True, True])
>>> x2 = np.array([False, True])
>>> x1 ^ x2
array([ True, False])
ceil = <numpy.ma.core._MaskedUnaryOperation object>
ceil(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the ceiling of the input, element-wise.
The ceil of the scalar `x` is the smallest integer `i`, such that
``i >= x``. It is often denoted as :math:`\lceil x \rceil`.
Parameters
----------
x : array_like
Input data.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The ceiling of each element in `x`.
This is a scalar if `x` is a scalar.
See Also
--------
floor, trunc, rint, fix
Examples
--------
>>> import numpy as np
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.ceil(a)
array([-1., -1., -0., 1., 2., 2., 2.])
clip = <numpy.ma.core._convert2ma object>
Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to
the interval edges. For example, if an interval of ``[0, 1]``
is specified, values smaller than 0 become 0, and values larger
than 1 become 1.
Equivalent to but faster than ``np.minimum(a_max, np.maximum(a, a_min))``.
No check is performed to ensure ``a_min < a_max``.
Parameters
----------
a : array_like
Array containing elements to clip.
a_min, a_max : array_like or None
Minimum and maximum value. If ``None``, clipping is not performed on
the corresponding edge. If both ``a_min`` and ``a_max`` are ``None``,
the elements of the returned array stay the same. Both are broadcasted
against ``a``.
out : ndarray, optional
The results will be placed in this array. It may be the input
array for in-place clipping. `out` must be of the right shape
to hold the output. Its type is preserved.
min, max : array_like or None
Array API compatible alternatives for ``a_min`` and ``a_max``
arguments. Either ``a_min`` and ``a_max`` or ``min`` and ``max``
can be passed at the same time. Default: ``None``.
.. versionadded:: 2.1.0
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
.. versionadded:: 1.17.0
Returns
-------
clipped_array : MaskedArray
An array with the elements of `a`, but where values
< `a_min` are replaced with `a_min`, and those > `a_max`
with `a_max`.
See Also
--------
:ref:`ufuncs-output-type`
Notes
-----
When `a_min` is greater than `a_max`, `clip` returns an
array in which all values are equal to `a_max`,
as shown in the second example.
Examples
--------
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, 1, 8)
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> np.clip(a, 8, 1)
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
>>> np.clip(a, 3, 6, out=a)
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8)
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
column_stack = <numpy.ma.extras._fromnxfunction_seq object>
Stack 1-D arrays as columns into a 2-D array.
Take a sequence of 1-D arrays and stack them as columns
to make a single 2-D array. 2-D arrays are stacked as-is,
just like with `hstack`. 1-D arrays are turned into 2-D columns
first.
Parameters
----------
tup : sequence of 1-D or 2-D arrays.
Arrays to stack. All of them must have the same first dimension.
Returns
-------
stacked : 2-D array
The array formed by stacking the given arrays.
See Also
--------
stack, hstack, vstack, concatenate
Examples
--------
>>> import numpy as np
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
Notes
-----
The function is applied to both the _data and the _mask, if any.
compress = <numpy.ma.core._frommethod object>
compress(self, condition, axis=None, out=None)
Return `a` where condition is ``True``.
If condition is a `~ma.MaskedArray`, missing values are considered
as ``False``.
Parameters
----------
condition : var
Boolean 1-d array selecting which entries to return. If len(condition)
is less than the size of a along the axis, then output is truncated
to length of condition array.
axis : {None, int}, optional
Axis along which the operation must be performed.
out : {None, ndarray}, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
result : MaskedArray
A :class:`~ma.MaskedArray` object.
Notes
-----
Please note the difference with :meth:`compressed` !
The output of :meth:`compress` has a mask, the output of
:meth:`compressed` does not.
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> x
masked_array(
data=[[1, --, 3],
[--, 5, --],
[7, --, 9]],
mask=[[False, True, False],
[ True, False, True],
[False, True, False]],
fill_value=999999)
>>> x.compress([1, 0, 1])
masked_array(data=[1, 3],
mask=[False, False],
fill_value=999999)
>>> x.compress([1, 0, 1], axis=1)
masked_array(
data=[[1, 3],
[--, --],
[7, 9]],
mask=[[False, False],
[ True, True],
[False, False]],
fill_value=999999)
conjugate = <numpy.ma.core._MaskedUnaryOperation object>
conjugate(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the complex conjugate, element-wise.
The complex conjugate of a complex number is obtained by changing the
sign of its imaginary part.
Parameters
----------
x : array_like
Input value.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The complex conjugate of `x`, with same dtype as `y`.
This is a scalar if `x` is a scalar.
Notes
-----
`conj` is an alias for `conjugate`:
>>> np.conj is np.conjugate
True
Examples
--------
>>> import numpy as np
>>> np.conjugate(1+2j)
(1-2j)
>>> x = np.eye(2) + 1j * np.eye(2)
>>> np.conjugate(x)
array([[ 1.-1.j, 0.-0.j],
[ 0.-0.j, 1.-1.j]])
copy = <numpy.ma.core._frommethod object>
copy(self, *args, **params)
a.copy(order='C')
Return a copy of the array.
Parameters
----------
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout of the copy. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'C' otherwise. 'K' means match the layout of `a` as closely
as possible. (Note that this function and :func:`numpy.copy` are very
similar but have different default values for their order=
arguments, and this function always passes sub-classes through.)
See also
--------
numpy.copy : Similar function with different default behavior
numpy.copyto
Notes
-----
This function is the preferred method for creating an array copy. The
function :func:`numpy.copy` is similar, but it defaults to using order 'K',
and will not pass sub-classes through by default.
Examples
--------
>>> import numpy as np
>>> x = np.array([[1,2,3],[4,5,6]], order='F')
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags['C_CONTIGUOUS']
True
For arrays containing Python objects (e.g. dtype=object),
the copy is a shallow one. The new array will contain the
same object which may lead to surprises if that object can
be modified (is mutable):
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> b = a.copy()
>>> b[2][0] = 10
>>> a
array([1, 'm', list([10, 3, 4])], dtype=object)
To ensure all elements within an ``object`` array are copied,
use `copy.deepcopy`:
>>> import copy
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> c = copy.deepcopy(a)
>>> c[2][0] = 10
>>> c
array([1, 'm', list([10, 3, 4])], dtype=object)
>>> a
array([1, 'm', list([2, 3, 4])], dtype=object)
cos = <numpy.ma.core._MaskedUnaryOperation object>
cos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Cosine element-wise.
Parameters
----------
x : array_like
Input array in radians.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding cosine values.
This is a scalar if `x` is a scalar.
Notes
-----
If `out` is provided, the function writes the result into it,
and returns a reference to `out`. (See Examples)
References
----------
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.
New York, NY: Dover, 1972.
Examples
--------
>>> import numpy as np
>>> np.cos(np.array([0, np.pi/2, np.pi]))
array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00])
>>>
>>> # Example of providing the optional output parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.cos([0.1], out1)
>>> out2 is out1
True
>>>
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.cos(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
cosh = <numpy.ma.core._MaskedUnaryOperation object>
cosh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Hyperbolic cosine, element-wise.
Equivalent to ``1/2 * (np.exp(x) + np.exp(-x))`` and ``np.cos(1j*x)``.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Output array of same shape as `x`.
This is a scalar if `x` is a scalar.
Examples
--------
>>> import numpy as np
>>> np.cosh(0)
1.0
The hyperbolic cosine describes the shape of a hanging cable:
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-4, 4, 1000)
>>> plt.plot(x, np.cosh(x))
>>> plt.show()
count = <numpy.ma.core._frommethod object>
count(self, axis=None, keepdims=<no value>)
Count the non-masked elements of the array along the given axis.
Parameters
----------
axis : None or int or tuple of ints, optional
Axis or axes along which the count is performed.
The default, None, performs the count over all
the dimensions of the input array. `axis` may be negative, in
which case it counts from the last to the first axis.
.. versionadded:: 1.10.0
If this is a tuple of ints, the count is performed on multiple
axes, instead of a single axis or all the axes as before.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.
Returns
-------
result : ndarray or scalar
An array with the same shape as the input array, with the specified
axis removed. If the array is a 0-d array, or if `axis` is None, a
scalar is returned.
See Also
--------
ma.count_masked : Count masked elements in array or along a given axis.
Examples
--------
>>> import numpy.ma as ma
>>> a = ma.arange(6).reshape((2, 3))
>>> a[1, :] = ma.masked
>>> a
masked_array(
data=[[0, 1, 2],
[--, --, --]],
mask=[[False, False, False],
[ True, True, True]],
fill_value=999999)
>>> a.count()
3
When the `axis` keyword is specified an array of appropriate size is
returned.
>>> a.count(axis=0)
array([1, 1, 1])
>>> a.count(axis=1)
array([3, 0])
cumprod = <numpy.ma.core._frommethod object>
cumprod(self, axis=None, dtype=None, out=None)
Return the cumulative product of the array elements over the given axis.
Masked values are set to 1 internally during the computation.
However, their position is saved, and the result will be masked at
the same locations.
Refer to `numpy.cumprod` for full documentation.
Notes
-----
The mask is lost if `out` is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is
raised on overflow.
See Also
--------
numpy.ndarray.cumprod : corresponding function for ndarrays
numpy.cumprod : equivalent function
cumsum = <numpy.ma.core._frommethod object>
cumsum(self, axis=None, dtype=None, out=None)
Return the cumulative sum of the array elements over the given axis.
Masked values are set to 0 internally during the computation.
However, their position is saved, and the result will be masked at
the same locations.
Refer to `numpy.cumsum` for full documentation.
Notes
-----
The mask is lost if `out` is not a valid :class:`ma.MaskedArray` !
Arithmetic is modular when using integer types, and no error is
raised on overflow.
See Also
--------
numpy.ndarray.cumsum : corresponding function for ndarrays
numpy.cumsum : equivalent function
Examples
--------
>>> import numpy as np
>>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
>>> marr.cumsum()
masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33],
mask=[False, False, False, True, True, True, False, False,
False, False],
fill_value=999999)
diagflat = <numpy.ma.extras._fromnxfunction_single object>
Create a two-dimensional array with the flattened input as a diagonal.
Parameters
----------
v : array_like
Input data, which is flattened and set as the `k`-th
diagonal of the output.
k : int, optional
Diagonal to set; 0, the default, corresponds to the "main" diagonal,
a positive (negative) `k` giving the number of the diagonal above
(below) the main.
Returns
-------
out : ndarray
The 2-D output array.
See Also
--------
diag : MATLAB work-alike for 1-D and 2-D arrays.
diagonal : Return specified diagonals.
trace : Sum along diagonals.
Examples
--------
>>> import numpy as np
>>> np.diagflat([[1,2], [3,4]])
array([[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, 0, 0, 4]])
>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
[0, 0, 2],
[0, 0, 0]])
Notes
-----
The function is applied to both the _data and the _mask, if any.
diagonal = <numpy.ma.core._frommethod object>
diagonal(self, *args, **params)
a.diagonal(offset=0, axis1=0, axis2=1)
Return specified diagonals. In NumPy 1.9 the returned array is a
read-only view instead of a copy as in previous NumPy versions. In
a future version the read-only restriction will be removed.
Refer to :func:`numpy.diagonal` for full documentation.
See Also
--------
numpy.diagonal : equivalent function
divide = <numpy.ma.core._DomainedBinaryOperation object>
divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Divide arguments element-wise.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The quotient ``x1/x2``, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
seterr : Set whether to raise or warn on overflow, underflow and
division by zero.
Notes
-----
Equivalent to ``x1`` / ``x2`` in terms of array-broadcasting.
The ``true_divide(x1, x2)`` function is an alias for
``divide(x1, x2)``.
Examples
--------
>>> import numpy as np
>>> np.divide(2.0, 4.0)
0.5
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.divide(x1, x2)
array([[nan, 1. , 1. ],
[inf, 4. , 2.5],
[inf, 7. , 4. ]])
The ``/`` operator can be used as a shorthand for ``np.divide`` on
ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = 2 * np.ones(3)
>>> x1 / x2
array([[0. , 0.5, 1. ],
[1.5, 2. , 2.5],
[3. , 3.5, 4. ]])
dstack = <numpy.ma.extras._fromnxfunction_seq object>
Stack arrays in sequence depth wise (along third axis).
This is equivalent to concatenation along the third axis after 2-D arrays
of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape
`(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by
`dsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of arrays
The arrays must have the same shape along all but the third axis.
1-D or 2-D arrays must have the same shape.
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 3-D.
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
block : Assemble an nd-array from nested lists of blocks.
vstack : Stack arrays in sequence vertically (row wise).
hstack : Stack arrays in sequence horizontally (column wise).
column_stack : Stack 1-D arrays as columns into a 2-D array.
dsplit : Split array along third axis.
Examples
--------
>>> import numpy as np
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
Notes
-----
The function is applied to both the _data and the _mask, if any.
empty = <numpy.ma.core._convert2ma object>
empty(shape, dtype=float, order='C', *, device=None, like=None)
Return a new array of given shape and type, without initializing entries.
Parameters
----------
shape : int or tuple of int
Shape of the empty array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
Desired output data-type for the array, e.g, `numpy.int8`. Default is
`numpy.float64`.
order : {'C', 'F'}, optional, default: 'C'
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
device : str, optional
The device on which to place the created array. Default: ``None``.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : MaskedArray
Array of uninitialized (arbitrary) data of the given shape, dtype, and
order. Object arrays will be initialized to None.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones : Return a new array setting values to one.
zeros : Return a new array setting values to zero.
full : Return a new array of given shape filled with value.
Notes
-----
Unlike other array creation functions (e.g. `zeros`, `ones`, `full`),
`empty` does not initialize the values of the array, and may therefore be
marginally faster. However, the values stored in the newly allocated array
are arbitrary. For reproducible behavior, be sure to set each element of
the array before reading.
Examples
--------
>>> import numpy as np
>>> np.empty([2, 2])
array([[ -9.74499359e+001, 6.69583040e-309],
[ 2.13182611e-314, 3.06959433e-309]]) #uninitialized
>>> np.empty([2, 2], dtype=int)
array([[-1073741821, -1067949133],
[ 496041986, 19249760]]) #uninitialized
empty_like = <numpy.ma.core._convert2ma object>
empty_like(prototype, dtype=None, order='K', subok=True, shape=None, *,
device=None)
Return a new array with the same shape and type as a given array.
Parameters
----------
prototype : array_like
The shape and data-type of `prototype` define these same attributes
of the returned array.
dtype : data-type, optional
Overrides the data type of the result.
.. versionadded:: 1.6.0
order : {'C', 'F', 'A', or 'K'}, optional
Overrides the memory layout of the result. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `prototype` is Fortran
contiguous, 'C' otherwise. 'K' means match the layout of `prototype`
as closely as possible.
.. versionadded:: 1.6.0
subok : bool, optional.
If True, then the newly created array will use the sub-class
type of `prototype`, otherwise it will be a base-class array. Defaults
to True.
shape : int 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.
.. versionadded:: 1.17.0
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
out : MaskedArray
Array of uninitialized (arbitrary) data with the same
shape and type as `prototype`.
See Also
--------
ones_like : Return an array of ones with shape and type of input.
zeros_like : Return an array of zeros with shape and type of input.
full_like : Return a new array with shape of input filled with value.
empty : Return a new uninitialized array.
Notes
-----
Unlike other array creation functions (e.g. `zeros_like`, `ones_like`,
`full_like`), `empty_like` does not initialize the values of the array,
and may therefore be marginally faster. However, the values stored in the
newly allocated array are arbitrary. For reproducible behavior, be sure
to set each element of the array before reading.
Examples
--------
>>> import numpy as np
>>> a = ([1,2,3], [4,5,6]) # a is array-like
>>> np.empty_like(a)
array([[-1073741821, -1073741821, 3], # uninitialized
[ 0, 0, -1073741821]])
>>> a = np.array([[1., 2., 3.],[4.,5.,6.]])
>>> np.empty_like(a)
array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninitialized
[ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]])
equal = <numpy.ma.core._MaskedBinaryOperation object>
equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return (x1 == x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Output array, element-wise comparison of `x1` and `x2`.
Typically of type bool, unless ``dtype=object`` is passed.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
not_equal, greater_equal, less_equal, greater, less
Examples
--------
>>> import numpy as np
>>> np.equal([0, 1, 3], np.arange(3))
array([ True, True, False])
What is compared are values, not types. So an int (1) and an array of
length one can evaluate as True:
>>> np.equal(1, np.ones(1))
array([ True])
The ``==`` operator can be used as a shorthand for ``np.equal`` on
ndarrays.
>>> a = np.array([2, 4, 6])
>>> b = np.array([2, 4, 2])
>>> a == b
array([ True, True, False])
exp = <numpy.ma.core._MaskedUnaryOperation object>
exp(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Calculate the exponential of all elements in the input array.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Output array, element-wise exponential of `x`.
This is a scalar if `x` is a scalar.
See Also
--------
expm1 : Calculate ``exp(x) - 1`` for all elements in the array.
exp2 : Calculate ``2**x`` for all elements in the array.
Notes
-----
The irrational number ``e`` is also known as Euler's number. It is
approximately 2.718281, and is the base of the natural logarithm,
``ln`` (this means that, if :math:`x = \ln y = \log_e y`,
then :math:`e^x = y`. For real input, ``exp(x)`` is always positive.
For complex arguments, ``x = a + ib``, we can write
:math:`e^x = e^a e^{ib}`. The first term, :math:`e^a`, is already
known (it is the real argument, described above). The second term,
:math:`e^{ib}`, is :math:`\cos b + i \sin b`, a function with
magnitude 1 and a periodic phase.
References
----------
.. [1] Wikipedia, "Exponential function",
https://en.wikipedia.org/wiki/Exponential_function
.. [2] M. Abramovitz and I. A. Stegun, "Handbook of Mathematical Functions
with Formulas, Graphs, and Mathematical Tables," Dover, 1964, p. 69,
https://personal.math.ubc.ca/~cbm/aands/page_69.htm
Examples
--------
Plot the magnitude and phase of ``exp(x)`` in the complex plane:
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-2*np.pi, 2*np.pi, 100)
>>> xx = x + 1j * x[:, np.newaxis] # a + ib over complex plane
>>> out = np.exp(xx)
>>> plt.subplot(121)
>>> plt.imshow(np.abs(out),
... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap='gray')
>>> plt.title('Magnitude of exp(x)')
>>> plt.subplot(122)
>>> plt.imshow(np.angle(out),
... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi], cmap='hsv')
>>> plt.title('Phase (angle) of exp(x)')
>>> plt.show()
fabs = <numpy.ma.core._MaskedUnaryOperation object>
fabs(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the absolute values element-wise.
This function returns the absolute values (positive magnitude) of the
data in `x`. Complex values are not handled, use `absolute` to find the
absolute values of complex data.
Parameters
----------
x : array_like
The array of numbers for which the absolute values are required. If
`x` is a scalar, the result `y` will also be a scalar.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The absolute values of `x`, the returned values are always floats.
This is a scalar if `x` is a scalar.
See Also
--------
absolute : Absolute values including `complex` types.
Examples
--------
>>> import numpy as np
>>> np.fabs(-1)
1.0
>>> np.fabs([-1.2, 1.2])
array([ 1.2, 1.2])
floor = <numpy.ma.core._MaskedUnaryOperation object>
floor(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the floor of the input, element-wise.
The floor of the scalar `x` is the largest integer `i`, such that
`i <= x`. It is often denoted as :math:`\lfloor x \rfloor`.
Parameters
----------
x : array_like
Input data.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The floor of each element in `x`.
This is a scalar if `x` is a scalar.
See Also
--------
ceil, trunc, rint, fix
Notes
-----
Some spreadsheet programs calculate the "floor-towards-zero", where
``floor(-2.5) == -2``. NumPy instead uses the definition of
`floor` where `floor(-2.5) == -3`. The "floor-towards-zero"
function is called ``fix`` in NumPy.
Examples
--------
>>> import numpy as np
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.floor(a)
array([-2., -2., -1., 0., 1., 1., 2.])
floor_divide = <numpy.ma.core._DomainedBinaryOperation object>
floor_divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the largest integer smaller or equal to the division of the inputs.
It is equivalent to the Python ``//`` operator and pairs with the
Python ``%`` (`remainder`), function so that ``a = a % b + b * (a // b)``
up to roundoff.
Parameters
----------
x1 : array_like
Numerator.
x2 : array_like
Denominator.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
y = floor(`x1`/`x2`)
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
remainder : Remainder complementary to floor_divide.
divmod : Simultaneous floor division and remainder.
divide : Standard division.
floor : Round a number to the nearest integer toward minus infinity.
ceil : Round a number to the nearest integer toward infinity.
Examples
--------
>>> import numpy as np
>>> np.floor_divide(7,3)
2
>>> np.floor_divide([1., 2., 3., 4.], 2.5)
array([ 0., 0., 1., 1.])
The ``//`` operator can be used as a shorthand for ``np.floor_divide``
on ndarrays.
>>> x1 = np.array([1., 2., 3., 4.])
>>> x1 // 2.5
array([0., 0., 1., 1.])
fmod = <numpy.ma.core._DomainedBinaryOperation object>
fmod(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns the element-wise remainder of division.
This is the NumPy implementation of the C library function fmod, the
remainder has the same sign as the dividend `x1`. It is equivalent to
the Matlab(TM) ``rem`` function and should not be confused with the
Python modulus operator ``x1 % x2``.
Parameters
----------
x1 : array_like
Dividend.
x2 : array_like
Divisor.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : array_like
The remainder of the division of `x1` by `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
remainder : Equivalent to the Python ``%`` operator.
divide
Notes
-----
The result of the modulo operation for negative dividend and divisors
is bound by conventions. For `fmod`, the sign of result is the sign of
the dividend, while for `remainder` the sign of the result is the sign
of the divisor. The `fmod` function is equivalent to the Matlab(TM)
``rem`` function.
Examples
--------
>>> import numpy as np
>>> np.fmod([-3, -2, -1, 1, 2, 3], 2)
array([-1, 0, -1, 1, 0, 1])
>>> np.remainder([-3, -2, -1, 1, 2, 3], 2)
array([1, 0, 1, 1, 0, 1])
>>> np.fmod([5, 3], [2, 2.])
array([ 1., 1.])
>>> a = np.arange(-3, 3).reshape(3, 2)
>>> a
array([[-3, -2],
[-1, 0],
[ 1, 2]])
>>> np.fmod(a, [2,2])
array([[-1, 0],
[-1, 0],
[ 1, 0]])
frombuffer = <numpy.ma.core._convert2ma object>
frombuffer(buffer, dtype=float, count=-1, offset=0, *, like=None)
Interpret a buffer as a 1-dimensional array.
Parameters
----------
buffer : buffer_like
An object that exposes the buffer interface.
dtype : data-type, optional
Data-type of the returned array; default: float.
count : int, optional
Number of items to read. ``-1`` means all data in the buffer.
offset : int, optional
Start reading the buffer from this offset (in bytes); default: 0.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out: MaskedArray
See also
--------
ndarray.tobytes
Inverse of this operation, construct Python bytes from the raw data
bytes in the array.
Notes
-----
If the buffer has data that is not in machine byte-order, this should
be specified as part of the data-type, e.g.::
>>> dt = np.dtype(int)
>>> dt = dt.newbyteorder('>')
>>> np.frombuffer(buf, dtype=dt) # doctest: +SKIP
The data of the resulting array will not be byteswapped, but will be
interpreted correctly.
This function creates a view into the original object. This should be safe
in general, but it may make sense to copy the result when the original
object is mutable or untrusted.
Examples
--------
>>> import numpy as np
>>> s = b'hello world'
>>> np.frombuffer(s, dtype='S1', count=5, offset=6)
array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')
>>> np.frombuffer(b'\x01\x02', dtype=np.uint8)
array([1, 2], dtype=uint8)
>>> np.frombuffer(b'\x01\x02\x03\x04\x05', dtype=np.uint8, count=3)
array([1, 2, 3], dtype=uint8)
fromfunction = <numpy.ma.core._convert2ma object>
fromfunction(function, shape, **dtype)
Construct an array by executing a function over each coordinate.
The resulting array therefore has a value ``fn(x, y, z)`` at
coordinate ``(x, y, z)``.
Parameters
----------
function : callable
The function is called with N parameters, where N is the rank of
`shape`. Each parameter represents the coordinates of the array
varying along a specific axis. For example, if `shape`
were ``(2, 2)``, then the parameters would be
``array([[0, 0], [1, 1]])`` and ``array([[0, 1], [0, 1]])``
shape : (N,) tuple of ints
Shape of the output array, which also determines the shape of
the coordinate arrays passed to `function`.
dtype : data-type, optional
Data-type of the coordinate arrays passed to `function`.
By default, `dtype` is float.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
fromfunction: MaskedArray
The result of the call to `function` is passed back directly.
Therefore the shape of `fromfunction` is completely determined by
`function`. If `function` returns a scalar value, the shape of
`fromfunction` would not match the `shape` parameter.
See Also
--------
indices, meshgrid
Notes
-----
Keywords other than `dtype` and `like` are passed to `function`.
Examples
--------
>>> import numpy as np
>>> np.fromfunction(lambda i, j: i, (2, 2), dtype=float)
array([[0., 0.],
[1., 1.]])
>>> np.fromfunction(lambda i, j: j, (2, 2), dtype=float)
array([[0., 1.],
[0., 1.]])
>>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
array([[ True, False, False],
[False, True, False],
[False, False, True]])
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
greater = <numpy.ma.core._MaskedBinaryOperation object>
greater(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 > x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
greater_equal, less, less_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.greater([4,2],[2,2])
array([ True, False])
The ``>`` operator can be used as a shorthand for ``np.greater`` on
ndarrays.
>>> a = np.array([4, 2])
>>> b = np.array([2, 2])
>>> a > b
array([ True, False])
greater_equal = <numpy.ma.core._MaskedBinaryOperation object>
greater_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 >= x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : bool or ndarray of bool
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
--------
greater, less, less_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.greater_equal([4, 2, 1], [2, 2, 2])
array([ True, True, False])
The ``>=`` operator can be used as a shorthand for ``np.greater_equal``
on ndarrays.
>>> a = np.array([4, 2, 1])
>>> b = np.array([2, 2, 2])
>>> a >= b
array([ True, True, False])
harden_mask = <numpy.ma.core._frommethod object>
harden_mask(self)
Force the mask to hard, preventing unmasking by assignment.
Whether the mask of a masked array is hard or soft is determined by
its `~ma.MaskedArray.hardmask` property. `harden_mask` sets
`~ma.MaskedArray.hardmask` to ``True`` (and returns the modified
self).
See Also
--------
ma.MaskedArray.hardmask
ma.MaskedArray.soften_mask
hsplit = <numpy.ma.extras._fromnxfunction_single object>
Split an array into multiple sub-arrays horizontally (column-wise).
Please refer to the `split` documentation. `hsplit` is equivalent
to `split` with ``axis=1``, the array is always split along the second
axis except for 1-D arrays, where it is split at ``axis=0``.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> import numpy as np
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.]])
>>> np.hsplit(x, 2)
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
[12., 13.]]),
array([[ 2., 3.],
[ 6., 7.],
[10., 11.],
[14., 15.]])]
>>> np.hsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2.],
[ 4., 5., 6.],
[ 8., 9., 10.],
[12., 13., 14.]]),
array([[ 3.],
[ 7.],
[11.],
[15.]]),
array([], shape=(4, 0), dtype=float64)]
With a higher dimensional array the split is still along the second axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[0., 1.],
[2., 3.]],
[[4., 5.],
[6., 7.]]])
>>> np.hsplit(x, 2)
[array([[[0., 1.]],
[[4., 5.]]]),
array([[[2., 3.]],
[[6., 7.]]])]
With a 1-D array, the split is along axis 0.
>>> x = np.array([0, 1, 2, 3, 4, 5])
>>> np.hsplit(x, 2)
[array([0, 1, 2]), array([3, 4, 5])]
Notes
-----
The function is applied to both the _data and the _mask, if any.
hstack = <numpy.ma.extras._fromnxfunction_seq object>
Stack arrays in sequence horizontally (column wise).
This is equivalent to concatenation along the second axis, except for 1-D
arrays where it concatenates along the first axis. Rebuilds arrays divided
by `hsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of ndarrays
The arrays must have the same shape along all but the second axis,
except 1-D arrays which can be any length.
dtype : str or dtype
If provided, the destination array will have this dtype. Cannot be
provided together with `out`.
.. versionadded:: 1.24
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'same_kind'.
.. versionadded:: 1.24
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays.
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
block : Assemble an nd-array from nested lists of blocks.
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third axis).
column_stack : Stack 1-D arrays as columns into a 2-D array.
hsplit : Split an array into multiple sub-arrays
horizontally (column-wise).
unstack : Split an array into a tuple of sub-arrays along an axis.
Examples
--------
>>> import numpy as np
>>> a = np.array((1,2,3))
>>> b = np.array((4,5,6))
>>> np.hstack((a,b))
array([1, 2, 3, 4, 5, 6])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[4],[5],[6]])
>>> np.hstack((a,b))
array([[1, 4],
[2, 5],
[3, 6]])
Notes
-----
The function is applied to both the _data and the _mask, if any.
hypot = <numpy.ma.core._MaskedBinaryOperation object>
hypot(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Given the "legs" of a right triangle, return its hypotenuse.
Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or
`x2` is scalar_like (i.e., unambiguously cast-able to a scalar type),
it is broadcast for use with each element of the other argument.
(See Examples)
Parameters
----------
x1, x2 : array_like
Leg of the triangle(s).
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
z : ndarray
The hypotenuse of the triangle(s).
This is a scalar if both `x1` and `x2` are scalars.
Examples
--------
>>> import numpy as np
>>> np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3)))
array([[ 5., 5., 5.],
[ 5., 5., 5.],
[ 5., 5., 5.]])
Example showing broadcast of scalar_like argument:
>>> np.hypot(3*np.ones((3, 3)), [4])
array([[ 5., 5., 5.],
[ 5., 5., 5.],
[ 5., 5., 5.]])
identity = <numpy.ma.core._convert2ma object>
identity(n, dtype=None)
Return the identity array.
The identity array is a square array with ones on
the main diagonal.
Parameters
----------
n : int
Number of rows (and columns) in `n` x `n` output.
dtype : data-type, optional
Data-type of the output. Defaults to ``float``.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : MaskedArray
`n` x `n` array with its main diagonal set to one,
and all other elements 0.
Examples
--------
>>> import numpy as np
>>> np.identity(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
ids = <numpy.ma.core._frommethod object>
ids(self)
Return the addresses of the data and mask areas.
Parameters
----------
None
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1])
>>> x.ids()
(166670640, 166659832) # may vary
If the array has no mask, the address of `nomask` is returned. This address
is typically not close to the data in memory:
>>> x = np.ma.array([1, 2, 3])
>>> x.ids()
(166691080, 3083169284) # may vary
indices = <numpy.ma.core._convert2ma object>
indices(dimensions, dtype=<class 'int'>, sparse=False)
Return an array representing the indices of a grid.
Compute an array where the subarrays contain index values 0, 1, ...
varying only along the corresponding axis.
Parameters
----------
dimensions : sequence of ints
The shape of the grid.
dtype : dtype, optional
Data type of the result.
sparse : boolean, optional
Return a sparse representation of the grid instead of a dense
representation. Default is False.
.. versionadded:: 1.17
Returns
-------
grid : one MaskedArray or tuple of MaskedArrays
If sparse is False:
Returns one array of grid indices,
``grid.shape = (len(dimensions),) + tuple(dimensions)``.
If sparse is True:
Returns a tuple of arrays, with
``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
dimensions[i] in the ith place
See Also
--------
mgrid, ogrid, meshgrid
Notes
-----
The output shape in the dense case is obtained by prepending the number
of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
``(N, r0, ..., rN-1)``.
The subarrays ``grid[k]`` contains the N-D array of indices along the
``k-th`` axis. Explicitly::
grid[k, i0, i1, ..., iN-1] = ik
Examples
--------
>>> import numpy as np
>>> grid = np.indices((2, 3))
>>> grid.shape
(2, 2, 3)
>>> grid[0] # row indices
array([[0, 0, 0],
[1, 1, 1]])
>>> grid[1] # column indices
array([[0, 1, 2],
[0, 1, 2]])
The indices can be used as an index into an array.
>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0, 1, 2],
[4, 5, 6]])
Note that it would be more straightforward in the above example to
extract the required elements directly with ``x[:2, :3]``.
If sparse is set to true, the grid will be returned in a sparse
representation.
>>> i, j = np.indices((2, 3), sparse=True)
>>> i.shape
(2, 1)
>>> j.shape
(1, 3)
>>> i # row indices
array([[0],
[1]])
>>> j # column indices
array([[0, 1, 2]])
less = <numpy.ma.core._MaskedBinaryOperation object>
less(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 < x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
greater, less_equal, greater_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.less([1, 2], [2, 2])
array([ True, False])
The ``<`` operator can be used as a shorthand for ``np.less`` on ndarrays.
>>> a = np.array([1, 2])
>>> b = np.array([2, 2])
>>> a < b
array([ True, False])
less_equal = <numpy.ma.core._MaskedBinaryOperation object>
less_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 <= x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
greater, less, greater_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.less_equal([4, 2, 1], [2, 2, 2])
array([False, True, True])
The ``<=`` operator can be used as a shorthand for ``np.less_equal`` on
ndarrays.
>>> a = np.array([4, 2, 1])
>>> b = np.array([2, 2, 2])
>>> a <= b
array([False, True, True])
log = <numpy.ma.core._MaskedUnaryOperation object>
log(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Natural logarithm, element-wise.
The natural logarithm `log` is the inverse of the exponential function,
so that `log(exp(x)) = x`. The natural logarithm is logarithm in base
`e`.
Parameters
----------
x : array_like
Input value.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The natural logarithm of `x`, element-wise.
This is a scalar if `x` is a scalar.
See Also
--------
log10, log2, log1p, emath.log
Notes
-----
Logarithm is a multivalued function: for each `x` there is an infinite
number of `z` such that `exp(z) = x`. The convention is to return the
`z` whose imaginary part lies in `(-pi, pi]`.
For real-valued input data types, `log` always returns real output. For
each value that cannot be expressed as a real number or infinity, it
yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `log` is a complex analytical function that
has a branch cut `[-inf, 0]` and is continuous from above on it. `log`
handles the floating-point negative zero as an infinitesimal negative
number, conforming to the C99 standard.
In the cases where the input has a negative real part and a very small
negative complex part (approaching 0), the result is so close to `-pi`
that it evaluates to exactly `-pi`.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 67.
https://personal.math.ubc.ca/~cbm/aands/page_67.htm
.. [2] Wikipedia, "Logarithm". https://en.wikipedia.org/wiki/Logarithm
Examples
--------
>>> import numpy as np
>>> np.log([1, np.e, np.e**2, 0])
array([ 0., 1., 2., -inf])
log10 = <numpy.ma.core._MaskedUnaryOperation object>
log10(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the base 10 logarithm of the input array, element-wise.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The logarithm to the base 10 of `x`, element-wise. NaNs are
returned where x is negative.
This is a scalar if `x` is a scalar.
See Also
--------
emath.log10
Notes
-----
Logarithm is a multivalued function: for each `x` there is an infinite
number of `z` such that `10**z = x`. The convention is to return the
`z` whose imaginary part lies in `(-pi, pi]`.
For real-valued input data types, `log10` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `log10` is a complex analytical function that
has a branch cut `[-inf, 0]` and is continuous from above on it.
`log10` handles the floating-point negative zero as an infinitesimal
negative number, conforming to the C99 standard.
In the cases where the input has a negative real part and a very small
negative complex part (approaching 0), the result is so close to `-pi`
that it evaluates to exactly `-pi`.
References
----------
.. [1] M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
10th printing, 1964, pp. 67.
https://personal.math.ubc.ca/~cbm/aands/page_67.htm
.. [2] Wikipedia, "Logarithm". https://en.wikipedia.org/wiki/Logarithm
Examples
--------
>>> import numpy as np
>>> np.log10([1e-15, -3.])
array([-15., nan])
log2 = <numpy.ma.core._MaskedUnaryOperation object>
log2(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Base-2 logarithm of `x`.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Base-2 logarithm of `x`.
This is a scalar if `x` is a scalar.
See Also
--------
log, log10, log1p, emath.log2
Notes
-----
.. versionadded:: 1.3.0
Logarithm is a multivalued function: for each `x` there is an infinite
number of `z` such that `2**z = x`. The convention is to return the `z`
whose imaginary part lies in `(-pi, pi]`.
For real-valued input data types, `log2` always returns real output.
For each value that cannot be expressed as a real number or infinity,
it yields ``nan`` and sets the `invalid` floating point error flag.
For complex-valued input, `log2` is a complex analytical function that
has a branch cut `[-inf, 0]` and is continuous from above on it. `log2`
handles the floating-point negative zero as an infinitesimal negative
number, conforming to the C99 standard.
In the cases where the input has a negative real part and a very small
negative complex part (approaching 0), the result is so close to `-pi`
that it evaluates to exactly `-pi`.
Examples
--------
>>> import numpy as np
>>> x = np.array([0, 1, 2, 2**4])
>>> np.log2(x)
array([-inf, 0., 1., 4.])
>>> xi = np.array([0+1.j, 1, 2+0.j, 4.j])
>>> np.log2(xi)
array([ 0.+2.26618007j, 0.+0.j , 1.+0.j , 2.+2.26618007j])
logical_and = <numpy.ma.core._MaskedBinaryOperation object>
logical_and(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the truth value of x1 AND x2 element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or bool
Boolean result of the logical AND operation applied to the elements
of `x1` and `x2`; the shape is determined by broadcasting.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_or, logical_not, logical_xor
bitwise_and
Examples
--------
>>> import numpy as np
>>> np.logical_and(True, False)
False
>>> np.logical_and([True, False], [False, False])
array([False, False])
>>> x = np.arange(5)
>>> np.logical_and(x>1, x<4)
array([False, False, True, True, False])
The ``&`` operator can be used as a shorthand for ``np.logical_and`` on
boolean ndarrays.
>>> a = np.array([True, False])
>>> b = np.array([False, False])
>>> a & b
array([False, False])
logical_not = <numpy.ma.core._MaskedUnaryOperation object>
logical_not(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the truth value of NOT x element-wise.
Parameters
----------
x : array_like
Logical NOT is applied to the elements of `x`.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : bool or ndarray of bool
Boolean result with the same shape as `x` of the NOT operation
on elements of `x`.
This is a scalar if `x` is a scalar.
See Also
--------
logical_and, logical_or, logical_xor
Examples
--------
>>> import numpy as np
>>> np.logical_not(3)
False
>>> np.logical_not([True, False, 0, 1])
array([False, True, True, False])
>>> x = np.arange(5)
>>> np.logical_not(x<3)
array([False, False, False, True, True])
logical_or = <numpy.ma.core._MaskedBinaryOperation object>
logical_or(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the truth value of x1 OR x2 element-wise.
Parameters
----------
x1, x2 : array_like
Logical OR is applied to the elements of `x1` and `x2`.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or bool
Boolean result of the logical OR operation applied to the elements
of `x1` and `x2`; the shape is determined by broadcasting.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_and, logical_not, logical_xor
bitwise_or
Examples
--------
>>> import numpy as np
>>> np.logical_or(True, False)
True
>>> np.logical_or([True, False], [False, False])
array([ True, False])
>>> x = np.arange(5)
>>> np.logical_or(x < 1, x > 3)
array([ True, False, False, False, True])
The ``|`` operator can be used as a shorthand for ``np.logical_or`` on
boolean ndarrays.
>>> a = np.array([True, False])
>>> b = np.array([False, False])
>>> a | b
array([ True, False])
logical_xor = <numpy.ma.core._MaskedBinaryOperation object>
logical_xor(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute the truth value of x1 XOR x2, element-wise.
Parameters
----------
x1, x2 : array_like
Logical XOR is applied to the elements of `x1` and `x2`.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : bool or ndarray of bool
Boolean result of the logical XOR operation applied to the elements
of `x1` and `x2`; the shape is determined by broadcasting.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
logical_and, logical_or, logical_not, bitwise_xor
Examples
--------
>>> import numpy as np
>>> np.logical_xor(True, False)
True
>>> np.logical_xor([True, True, False, False], [True, False, True, False])
array([False, True, True, False])
>>> x = np.arange(5)
>>> np.logical_xor(x < 1, x > 3)
array([ True, False, False, False, True])
Simple example showing support of broadcasting
>>> np.logical_xor(0, np.eye(2))
array([[ True, False],
[False, True]])
masked = masked
masked_print_option = --
masked_singleton = masked
maximum = <numpy.ma.core._extrema_operation object>
maximum(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Element-wise maximum of array elements.
Compare two arrays and return a new array containing the element-wise
maxima. If one of the elements being compared is a NaN, then that
element is returned. If both elements are NaNs then the first is
returned. The latter distinction is important for complex NaNs, which
are defined as at least one of the real or imaginary parts being a NaN.
The net effect is that NaNs are propagated.
Parameters
----------
x1, x2 : array_like
The arrays holding the elements to be compared.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The maximum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
minimum :
Element-wise minimum of two arrays, propagates NaNs.
fmax :
Element-wise maximum of two arrays, ignores NaNs.
amax :
The maximum value of an array along a given axis, propagates NaNs.
nanmax :
The maximum value of an array along a given axis, ignores NaNs.
fmin, amin, nanmin
Notes
-----
The maximum is equivalent to ``np.where(x1 >= x2, x1, x2)`` when
neither x1 nor x2 are nans, but it is faster and does proper
broadcasting.
Examples
--------
>>> import numpy as np
>>> np.maximum([2, 3, 4], [1, 5, 2])
array([2, 5, 4])
>>> np.maximum(np.eye(2), [0.5, 2]) # broadcasting
array([[ 1. , 2. ],
[ 0.5, 2. ]])
>>> np.maximum([np.nan, 0, np.nan], [0, np.nan, np.nan])
array([nan, nan, nan])
>>> np.maximum(np.inf, 1)
inf
mean = <numpy.ma.core._frommethod object>
mean(self, axis=None, dtype=None, out=None, keepdims=<no value>)
Returns the average of the array elements along given axis.
Masked entries are ignored, and result elements which are not
finite will be masked.
Refer to `numpy.mean` for full documentation.
See Also
--------
numpy.ndarray.mean : corresponding function for ndarrays
numpy.mean : Equivalent function
numpy.ma.average : Weighted average.
Examples
--------
>>> import numpy as np
>>> a = np.ma.array([1,2,3], mask=[False, False, True])
>>> a
masked_array(data=[1, 2, --],
mask=[False, False, True],
fill_value=999999)
>>> a.mean()
1.5
minimum = <numpy.ma.core._extrema_operation object>
minimum(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Element-wise minimum of array elements.
Compare two arrays and return a new array containing the element-wise
minima. If one of the elements being compared is a NaN, then that
element is returned. If both elements are NaNs then the first is
returned. The latter distinction is important for complex NaNs, which
are defined as at least one of the real or imaginary parts being a NaN.
The net effect is that NaNs are propagated.
Parameters
----------
x1, x2 : array_like
The arrays holding the elements to be compared.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The minimum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
maximum :
Element-wise maximum of two arrays, propagates NaNs.
fmin :
Element-wise minimum of two arrays, ignores NaNs.
amin :
The minimum value of an array along a given axis, propagates NaNs.
nanmin :
The minimum value of an array along a given axis, ignores NaNs.
fmax, amax, nanmax
Notes
-----
The minimum is equivalent to ``np.where(x1 <= x2, x1, x2)`` when
neither x1 nor x2 are NaNs, but it is faster and does proper
broadcasting.
Examples
--------
>>> import numpy as np
>>> np.minimum([2, 3, 4], [1, 5, 2])
array([1, 3, 2])
>>> np.minimum(np.eye(2), [0.5, 2]) # broadcasting
array([[ 0.5, 0. ],
[ 0. , 1. ]])
>>> np.minimum([np.nan, 0, np.nan],[0, np.nan, np.nan])
array([nan, nan, nan])
>>> np.minimum(-np.inf, 1)
-inf
mod = <numpy.ma.core._DomainedBinaryOperation object>
remainder(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns the element-wise remainder of division.
Computes the remainder complementary to the `floor_divide` function. It is
equivalent to the Python modulus operator ``x1 % x2`` and has the same sign
as the divisor `x2`. The MATLAB function equivalent to ``np.remainder``
is ``mod``.
.. warning::
This should not be confused with:
* Python 3.7's `math.remainder` and C's ``remainder``, which
computes the IEEE remainder, which are the complement to
``round(x1 / x2)``.
* The MATLAB ``rem`` function and or the C ``%`` operator which is the
complement to ``int(x1 / x2)``.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The element-wise remainder of the quotient ``floor_divide(x1, x2)``.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
floor_divide : Equivalent of Python ``//`` operator.
divmod : Simultaneous floor division and remainder.
fmod : Equivalent of the MATLAB ``rem`` function.
divide, floor
Notes
-----
Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of)
integers.
``mod`` is an alias of ``remainder``.
Examples
--------
>>> import numpy as np
>>> np.remainder([4, 7], [2, 3])
array([0, 1])
>>> np.remainder(np.arange(7), 5)
array([0, 1, 2, 3, 4, 0, 1])
The ``%`` operator can be used as a shorthand for ``np.remainder`` on
ndarrays.
>>> x1 = np.arange(7)
>>> x1 % 5
array([0, 1, 2, 3, 4, 0, 1])
mr_ = <numpy.ma.extras.mr_class object>
multiply = <numpy.ma.core._MaskedBinaryOperation object>
multiply(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Multiply arguments element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays to be multiplied.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The product of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` * `x2` in terms of array broadcasting.
Examples
--------
>>> import numpy as np
>>> np.multiply(2.0, 4.0)
8.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.multiply(x1, x2)
array([[ 0., 1., 4.],
[ 0., 4., 10.],
[ 0., 7., 16.]])
The ``*`` operator can be used as a shorthand for ``np.multiply`` on
ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 * x2
array([[ 0., 1., 4.],
[ 0., 4., 10.],
[ 0., 7., 16.]])
negative = <numpy.ma.core._MaskedUnaryOperation object>
negative(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Numerical negative, element-wise.
Parameters
----------
x : array_like or scalar
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
Returned array or scalar: `y = -x`.
This is a scalar if `x` is a scalar.
Examples
--------
>>> import numpy as np
>>> 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.])
nomask = np.False_
nonzero = <numpy.ma.core._frommethod object>
nonzero(self)
Return the indices of unmasked elements that are not zero.
Returns a tuple of arrays, one for each dimension, containing the
indices of the non-zero elements in that dimension. The corresponding
non-zero values can be obtained with::
a[a.nonzero()]
To group the indices by element, rather than dimension, use
instead::
np.transpose(a.nonzero())
The result of this is always a 2d array, with a row for each non-zero
element.
Parameters
----------
None
Returns
-------
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also
--------
numpy.nonzero :
Function operating on ndarrays.
flatnonzero :
Return indices that are non-zero in the flattened version of the input
array.
numpy.ndarray.nonzero :
Equivalent ndarray method.
count_nonzero :
Counts the number of non-zero elements in the input array.
Examples
--------
>>> import numpy as np
>>> import numpy.ma as ma
>>> x = ma.array(np.eye(3))
>>> x
masked_array(
data=[[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]],
mask=False,
fill_value=1e+20)
>>> x.nonzero()
(array([0, 1, 2]), array([0, 1, 2]))
Masked elements are ignored.
>>> x[1, 1] = ma.masked
>>> x
masked_array(
data=[[1.0, 0.0, 0.0],
[0.0, --, 0.0],
[0.0, 0.0, 1.0]],
mask=[[False, False, False],
[False, True, False],
[False, False, False]],
fill_value=1e+20)
>>> x.nonzero()
(array([0, 2]), array([0, 2]))
Indices can also be grouped by element.
>>> np.transpose(x.nonzero())
array([[0, 0],
[2, 2]])
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, ma.nonzero(a > 3)
yields the indices of the `a` where the condition is true.
>>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
masked_array(
data=[[False, False, False],
[ True, True, True],
[ True, True, True]],
mask=False,
fill_value=True)
>>> ma.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
The ``nonzero`` method of the condition array can also be called.
>>> (a > 3).nonzero()
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
not_equal = <numpy.ma.core._MaskedBinaryOperation object>
not_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return (x1 != x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
>>> import numpy as np
>>> 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])
ones = <numpy.ma.core._convert2ma object>
ones(shape, dtype=None, order='C')
Return a new array of given shape and type, filled with ones.
Parameters
----------
shape : int or sequence of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
The desired data-type for the array, e.g., `numpy.int8`. Default is
`numpy.float64`.
order : {'C', 'F'}, optional, default: C
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : MaskedArray
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
--------
>>> import numpy as np
>>> 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.]])
ones_like = <numpy.ma.core._convert2ma object>
Return an array of ones with the same shape and type as a given array.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of
the returned array.
dtype : data-type, optional
Overrides the data type of the result.
.. versionadded:: 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.
.. versionadded:: 1.6.0
subok : bool, 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.
shape : int 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.
.. versionadded:: 1.17.0
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
out : MaskedArray
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
--------
>>> import numpy as np
>>> 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.])
prod = <numpy.ma.core._frommethod object>
prod(self, axis=None, dtype=None, out=None, keepdims=<no value>)
Return the product of the array elements over the given axis.
Masked elements are set to 1 internally for computation.
Refer to `numpy.prod` for full documentation.
Notes
-----
Arithmetic is modular when using integer types, and no error is raised
on overflow.
See Also
--------
numpy.ndarray.prod : corresponding function for ndarrays
numpy.prod : equivalent function
product = <numpy.ma.core._frommethod object>
prod(self, axis=None, dtype=None, out=None, keepdims=<no value>)
Return the product of the array elements over the given axis.
Masked elements are set to 1 internally for computation.
Refer to `numpy.prod` for full documentation.
Notes
-----
Arithmetic is modular when using integer types, and no error is raised
on overflow.
See Also
--------
numpy.ndarray.prod : corresponding function for ndarrays
numpy.prod : equivalent function
ravel = <numpy.ma.core._frommethod object>
ravel(self, order='C')
Returns a 1D version of self, as a view.
Parameters
----------
order : {'C', 'F', 'A', 'K'}, optional
The elements of `a` are read using this index order. 'C' means to
index the elements in C-like order, with the last axis index
changing fastest, back to the first axis index changing slowest.
'F' means to index the elements in Fortran-like index order, with
the first index changing fastest, and the last index changing
slowest. Note that the 'C' and 'F' options take no account of the
memory layout of the underlying array, and only refer to the order
of axis indexing. 'A' means to read the elements in Fortran-like
index order if `m` is Fortran *contiguous* in memory, C-like order
otherwise. 'K' means to read the elements in the order they occur
in memory, except for reversing the data when strides are negative.
By default, 'C' index order is used.
(Masked arrays currently use 'A' on the data when 'K' is passed.)
Returns
-------
MaskedArray
Output view is of shape ``(self.size,)`` (or
``(np.ma.product(self.shape),)``).
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> x
masked_array(
data=[[1, --, 3],
[--, 5, --],
[7, --, 9]],
mask=[[False, True, False],
[ True, False, True],
[False, True, False]],
fill_value=999999)
>>> x.ravel()
masked_array(data=[1, --, 3, --, 5, --, 7, --, 9],
mask=[False, True, False, True, False, True, False, True,
False],
fill_value=999999)
remainder = <numpy.ma.core._DomainedBinaryOperation object>
remainder(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns the element-wise remainder of division.
Computes the remainder complementary to the `floor_divide` function. It is
equivalent to the Python modulus operator ``x1 % x2`` and has the same sign
as the divisor `x2`. The MATLAB function equivalent to ``np.remainder``
is ``mod``.
.. warning::
This should not be confused with:
* Python 3.7's `math.remainder` and C's ``remainder``, which
computes the IEEE remainder, which are the complement to
``round(x1 / x2)``.
* The MATLAB ``rem`` function and or the C ``%`` operator which is the
complement to ``int(x1 / x2)``.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The element-wise remainder of the quotient ``floor_divide(x1, x2)``.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
floor_divide : Equivalent of Python ``//`` operator.
divmod : Simultaneous floor division and remainder.
fmod : Equivalent of the MATLAB ``rem`` function.
divide, floor
Notes
-----
Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of)
integers.
``mod`` is an alias of ``remainder``.
Examples
--------
>>> import numpy as np
>>> np.remainder([4, 7], [2, 3])
array([0, 1])
>>> np.remainder(np.arange(7), 5)
array([0, 1, 2, 3, 4, 0, 1])
The ``%`` operator can be used as a shorthand for ``np.remainder`` on
ndarrays.
>>> x1 = np.arange(7)
>>> x1 % 5
array([0, 1, 2, 3, 4, 0, 1])
repeat = <numpy.ma.core._frommethod object>
repeat(self, *args, **params)
a.repeat(repeats, axis=None)
Repeat elements of an array.
Refer to `numpy.repeat` for full documentation.
See Also
--------
numpy.repeat : equivalent function
row_stack = <numpy.ma.extras._fromnxfunction_seq object>
Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays
of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by
`vsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of ndarrays
The arrays must have the same shape along all but the first axis.
1-D arrays must have the same length.
dtype : str or dtype
If provided, the destination array will have this dtype. Cannot be
provided together with `out`.
.. versionadded:: 1.24
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'same_kind'.
.. versionadded:: 1.24
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 2-D.
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
block : Assemble an nd-array from nested lists of blocks.
hstack : Stack arrays in sequence horizontally (column wise).
dstack : Stack arrays in sequence depth wise (along third axis).
column_stack : Stack 1-D arrays as columns into a 2-D array.
vsplit : Split an array into multiple sub-arrays vertically (row-wise).
unstack : Split an array into a tuple of sub-arrays along an axis.
Examples
--------
>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.vstack((a,b))
array([[1, 2, 3],
[4, 5, 6]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[4], [5], [6]])
>>> np.vstack((a,b))
array([[1],
[2],
[3],
[4],
[5],
[6]])
Notes
-----
The function is applied to both the _data and the _mask, if any.
sin = <numpy.ma.core._MaskedUnaryOperation object>
sin(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Trigonometric sine, element-wise.
Parameters
----------
x : array_like
Angle, in radians (:math:`2 \pi` rad equals 360 degrees).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : array_like
The sine of each element of x.
This is a scalar if `x` is a scalar.
See Also
--------
arcsin, sinh, cos
Notes
-----
The sine is one of the fundamental functions of trigonometry (the
mathematical study of triangles). Consider a circle of radius 1
centered on the origin. A ray comes in from the :math:`+x` axis, makes
an angle at the origin (measured counter-clockwise from that axis), and
departs from the origin. The :math:`y` coordinate of the outgoing
ray's intersection with the unit circle is the sine of that angle. It
ranges from -1 for :math:`x=3\pi / 2` to +1 for :math:`\pi / 2.` The
function has zeroes where the angle is a multiple of :math:`\pi`.
Sines of angles between :math:`\pi` and :math:`2\pi` are negative.
The numerous properties of the sine and related functions are included
in any standard trigonometry text.
Examples
--------
>>> import numpy as np
Print sine of one angle:
>>> np.sin(np.pi/2.)
1.0
Print sines of an array of angles given in degrees:
>>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )
array([ 0. , 0.5 , 0.70710678, 0.8660254 , 1. ])
Plot the sine function:
>>> import matplotlib.pylab as plt
>>> x = np.linspace(-np.pi, np.pi, 201)
>>> plt.plot(x, np.sin(x))
>>> plt.xlabel('Angle [rad]')
>>> plt.ylabel('sin(x)')
>>> plt.axis('tight')
>>> plt.show()
sinh = <numpy.ma.core._MaskedUnaryOperation object>
sinh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Hyperbolic sine, element-wise.
Equivalent to ``1/2 * (np.exp(x) - np.exp(-x))`` or
``-1j * np.sin(1j*x)``.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding hyperbolic sine values.
This is a scalar if `x` is a scalar.
Notes
-----
If `out` is provided, the function writes the result into it,
and returns a reference to `out`. (See Examples)
References
----------
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.
New York, NY: Dover, 1972, pg. 83.
Examples
--------
>>> import numpy as np
>>> np.sinh(0)
0.0
>>> np.sinh(np.pi*1j/2)
1j
>>> np.sinh(np.pi*1j) # (exact value is 0)
1.2246063538223773e-016j
>>> # Discrepancy due to vagaries of floating point arithmetic.
>>> # Example of providing the optional output parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.sinh([0.1], out1)
>>> out2 is out1
True
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.sinh(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
soften_mask = <numpy.ma.core._frommethod object>
soften_mask(self)
Force the mask to soft (default), allowing unmasking by assignment.
Whether the mask of a masked array is hard or soft is determined by
its `~ma.MaskedArray.hardmask` property. `soften_mask` sets
`~ma.MaskedArray.hardmask` to ``False`` (and returns the modified
self).
See Also
--------
ma.MaskedArray.hardmask
ma.MaskedArray.harden_mask
sqrt = <numpy.ma.core._MaskedUnaryOperation object>
sqrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the non-negative square-root of an array, element-wise.
Parameters
----------
x : array_like
The values whose square-roots are required.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
An array of the same shape as `x`, containing the positive
square-root of each element in `x`. If any element in `x` is
complex, a complex array is returned (and the square-roots of
negative reals are calculated). If all of the elements in `x`
are real, so is `y`, with negative elements returning ``nan``.
If `out` was provided, `y` is a reference to it.
This is a scalar if `x` is a scalar.
See Also
--------
emath.sqrt
A version which returns complex numbers when given negative reals.
Note that 0.0 and -0.0 are handled differently for complex inputs.
Notes
-----
*sqrt* has--consistent with common convention--as its branch cut the
real "interval" [`-inf`, 0), and is continuous from above on it.
A branch cut is a curve in the complex plane across which a given
complex function fails to be continuous.
Examples
--------
>>> import numpy as np
>>> np.sqrt([1,4,9])
array([ 1., 2., 3.])
>>> np.sqrt([4, -1, -3+4J])
array([ 2.+0.j, 0.+1.j, 1.+2.j])
>>> np.sqrt([4, -1, np.inf])
array([ 2., nan, inf])
squeeze = <numpy.ma.core._convert2ma object>
Remove axes of length one from `a`.
Parameters
----------
a : array_like
Input data.
axis : None or int or tuple of ints, optional
.. versionadded:: 1.7.0
Selects a subset of the entries of length one in the
shape. If an axis is selected with shape entry greater than
one, an error is raised.
Returns
-------
squeezed : MaskedArray
The input array, but with all or a subset of the
dimensions of length 1 removed. This is always `a` itself
or a view into `a`. Note that if all axes are squeezed,
the result is a 0d array and not a scalar.
Raises
------
ValueError
If `axis` is not None, and an axis being squeezed is not of length 1
See Also
--------
expand_dims : The inverse operation, adding entries of length one
reshape : Insert, remove, and combine dimensions, and resize existing ones
Examples
--------
>>> import numpy as np
>>> x = np.array([[[0], [1], [2]]])
>>> x.shape
(1, 3, 1)
>>> np.squeeze(x).shape
(3,)
>>> np.squeeze(x, axis=0).shape
(3, 1)
>>> np.squeeze(x, axis=1).shape
Traceback (most recent call last):
...
ValueError: cannot select an axis to squeeze out which has size
not equal to one
>>> np.squeeze(x, axis=2).shape
(1, 3)
>>> x = np.array([[1234]])
>>> x.shape
(1, 1)
>>> np.squeeze(x)
array(1234) # 0d array
>>> np.squeeze(x).shape
()
>>> np.squeeze(x)[()]
1234
stack = <numpy.ma.extras._fromnxfunction_seq object>
Join a sequence of arrays along a new axis.
The ``axis`` parameter specifies the index of the new axis in the
dimensions of the result. For example, if ``axis=0`` it will be the first
dimension and if ``axis=-1`` it will be the last dimension.
.. versionadded:: 1.10.0
Parameters
----------
arrays : sequence of array_like
Each array must have the same shape.
axis : int, optional
The axis in the result array along which the input arrays are stacked.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what stack would have returned if no
out argument were specified.
dtype : str or dtype
If provided, the destination array will have this dtype. Cannot be
provided together with `out`.
.. versionadded:: 1.24
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'same_kind'.
.. versionadded:: 1.24
Returns
-------
stacked : ndarray
The stacked array has one more dimension than the input arrays.
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
block : Assemble an nd-array from nested lists of blocks.
split : Split array into a list of multiple sub-arrays of equal size.
unstack : Split an array into a tuple of sub-arrays along an axis.
Examples
--------
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> arrays = [rng.normal(size=(3,4)) for _ in range(10)]
>>> np.stack(arrays, axis=0).shape
(10, 3, 4)
>>> np.stack(arrays, axis=1).shape
(3, 10, 4)
>>> np.stack(arrays, axis=2).shape
(3, 4, 10)
>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.stack((a, b))
array([[1, 2, 3],
[4, 5, 6]])
>>> np.stack((a, b), axis=-1)
array([[1, 4],
[2, 5],
[3, 6]])
Notes
-----
The function is applied to both the _data and the _mask, if any.
std = <numpy.ma.core._frommethod object>
std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, mean=<no value>)
Returns the standard deviation of the array elements along given axis.
Masked entries are ignored.
Refer to `numpy.std` for full documentation.
See Also
--------
numpy.ndarray.std : corresponding function for ndarrays
numpy.std : Equivalent function
subtract = <numpy.ma.core._MaskedBinaryOperation object>
subtract(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Subtract arguments, element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be subtracted from each other.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The difference of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to ``x1 - x2`` in terms of array broadcasting.
Examples
--------
>>> import numpy as np
>>> np.subtract(1.0, 4.0)
-3.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.subtract(x1, x2)
array([[ 0., 0., 0.],
[ 3., 3., 3.],
[ 6., 6., 6.]])
The ``-`` operator can be used as a shorthand for ``np.subtract`` on
ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 - x2
array([[0., 0., 0.],
[3., 3., 3.],
[6., 6., 6.]])
sum = <numpy.ma.core._frommethod object>
sum(self, axis=None, dtype=None, out=None, keepdims=<no value>)
Return the sum of the array elements over the given axis.
Masked elements are set to 0 internally.
Refer to `numpy.sum` for full documentation.
See Also
--------
numpy.ndarray.sum : corresponding function for ndarrays
numpy.sum : equivalent function
Examples
--------
>>> import numpy as np
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> x
masked_array(
data=[[1, --, 3],
[--, 5, --],
[7, --, 9]],
mask=[[False, True, False],
[ True, False, True],
[False, True, False]],
fill_value=999999)
>>> x.sum()
25
>>> x.sum(axis=1)
masked_array(data=[4, 5, 16],
mask=[False, False, False],
fill_value=999999)
>>> x.sum(axis=0)
masked_array(data=[8, 5, 12],
mask=[False, False, False],
fill_value=999999)
>>> print(type(x.sum(axis=0, dtype=np.int64)[0]))
<class 'numpy.int64'>
swapaxes = <numpy.ma.core._frommethod object>
swapaxes(self, *args, **params)
a.swapaxes(axis1, axis2)
Return a view of the array with `axis1` and `axis2` interchanged.
Refer to `numpy.swapaxes` for full documentation.
See Also
--------
numpy.swapaxes : equivalent function
tan = <numpy.ma.core._MaskedUnaryOperation object>
tan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute tangent element-wise.
Equivalent to ``np.sin(x)/np.cos(x)`` element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding tangent values.
This is a scalar if `x` is a scalar.
Notes
-----
If `out` is provided, the function writes the result into it,
and returns a reference to `out`. (See Examples)
References
----------
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.
New York, NY: Dover, 1972.
Examples
--------
>>> import numpy as np
>>> from math import pi
>>> np.tan(np.array([-pi,pi/2,pi]))
array([ 1.22460635e-16, 1.63317787e+16, -1.22460635e-16])
>>>
>>> # Example of providing the optional output parameter illustrating
>>> # that what is returned is a reference to said parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.cos([0.1], out1)
>>> out2 is out1
True
>>>
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.cos(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
tanh = <numpy.ma.core._MaskedUnaryOperation object>
tanh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute hyperbolic tangent element-wise.
Equivalent to ``np.sinh(x)/np.cosh(x)`` or ``-1j * np.tan(1j*x)``.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding hyperbolic tangent values.
This is a scalar if `x` is a scalar.
Notes
-----
If `out` is provided, the function writes the result into it,
and returns a reference to `out`. (See Examples)
References
----------
.. [1] M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.
New York, NY: Dover, 1972, pg. 83.
https://personal.math.ubc.ca/~cbm/aands/page_83.htm
.. [2] Wikipedia, "Hyperbolic function",
https://en.wikipedia.org/wiki/Hyperbolic_function
Examples
--------
>>> import numpy as np
>>> np.tanh((0, np.pi*1j, np.pi*1j/2))
array([ 0. +0.00000000e+00j, 0. -1.22460635e-16j, 0. +1.63317787e+16j])
>>> # Example of providing the optional output parameter illustrating
>>> # that what is returned is a reference to said parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.tanh([0.1], out1)
>>> out2 is out1
True
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.tanh(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
trace = <numpy.ma.core._frommethod object>
trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None)
a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
Return the sum along diagonals of the array.
Refer to `numpy.trace` for full documentation.
See Also
--------
numpy.trace : equivalent function
true_divide = <numpy.ma.core._DomainedBinaryOperation object>
divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Divide arguments element-wise.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The quotient ``x1/x2``, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
seterr : Set whether to raise or warn on overflow, underflow and
division by zero.
Notes
-----
Equivalent to ``x1`` / ``x2`` in terms of array-broadcasting.
The ``true_divide(x1, x2)`` function is an alias for
``divide(x1, x2)``.
Examples
--------
>>> import numpy as np
>>> np.divide(2.0, 4.0)
0.5
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.divide(x1, x2)
array([[nan, 1. , 1. ],
[inf, 4. , 2.5],
[inf, 7. , 4. ]])
The ``/`` operator can be used as a shorthand for ``np.divide`` on
ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = 2 * np.ones(3)
>>> x1 / x2
array([[0. , 0.5, 1. ],
[1.5, 2. , 2.5],
[3. , 3.5, 4. ]])
var = <numpy.ma.core._frommethod object>
var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, mean=<no value>)
Compute the variance along the specified axis.
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.
Parameters
----------
a : array_like
Array containing numbers whose variance is desired. If `a` is not an
array, a conversion is attempted.
axis : None or int or tuple of ints, optional
Axis or axes along which the variance is computed. The default is to
compute the variance of the flattened array.
.. versionadded:: 1.7.0
If this is a tuple of ints, a variance is performed over multiple axes,
instead of a single axis or all the axes as before.
dtype : data-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.
out : ndarray, 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.
ddof : {int, float}, optional
"Delta Degrees of Freedom": the divisor used in the calculation is
``N - ddof``, where ``N`` represents the number of elements. By
default `ddof` is zero. See notes for details about use of `ddof`.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `var` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
where : array_like of bool, optional
Elements to include in the variance. See `~numpy.ufunc.reduce` for
details.
.. versionadded:: 1.20.0
mean : array like, optional
Provide the mean to prevent its recalculation. The mean should have
a shape as if it was calculated with ``keepdims=True``.
The axis for the calculation of the mean should be the same as used in
the call to this var function.
.. versionadded:: 1.26.0
correction : {int, float}, optional
Array API compatible name for the ``ddof`` parameter. Only one of them
can be provided at the same time.
.. versionadded:: 2.0.0
Returns
-------
variance : ndarray, see dtype parameter above
If ``out=None``, returns a new array containing the variance;
otherwise, a reference to the output array is returned.
See Also
--------
std, mean, nanmean, nanstd, nanvar
:ref:`ufuncs-output-type`
Notes
-----
There are several common variants of the array variance calculation.
Assuming the input `a` is a one-dimensional NumPy array and ``mean`` is
either provided as an argument or computed as ``a.mean()``, NumPy
computes the variance of an array as::
N = len(a)
d2 = abs(a - mean)**2 # abs is for complex `a`
var = d2.sum() / (N - ddof) # note use of `ddof`
Different values of the argument `ddof` are useful in different
contexts. NumPy's default ``ddof=0`` corresponds with the expression:
.. math::
\frac{\sum_i{|a_i - \bar{a}|^2 }}{N}
which is sometimes called the "population variance" in the field of
statistics because it applies the definition of variance to `a` as if `a`
were a complete population of possible observations.
Many other libraries define the variance of an array differently, e.g.:
.. math::
\frac{\sum_i{|a_i - \bar{a}|^2}}{N - 1}
In statistics, the resulting quantity is sometimed called the "sample
variance" because if `a` is a random sample from a larger population,
this calculation provides an unbiased estimate of the variance of the
population. The use of :math:`N-1` in the denominator is often called
"Bessel's correction" because it corrects for bias (toward lower values)
in the variance estimate introduced when the sample mean of `a` is used
in place of the true mean of the population. For this quantity, use
``ddof=1``.
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.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> np.var(a)
1.25
>>> np.var(a, axis=0)
array([1., 1.])
>>> np.var(a, axis=1)
array([0.25, 0.25])
In single precision, var() can be inaccurate:
>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.var(a)
0.20250003
Computing the variance in float64 is more accurate:
>>> np.var(a, dtype=np.float64)
0.20249999932944759 # may vary
>>> ((1-0.55)**2 + (0.1-0.55)**2)/2
0.2025
Specifying a where argument:
>>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
>>> np.var(a)
6.833333333333333 # may vary
>>> np.var(a, where=[[True], [True], [False]])
4.0
Using the mean keyword to save computation time:
>>> import numpy as np
>>> from timeit import timeit
>>>
>>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
>>> mean = np.mean(a, axis=1, keepdims=True)
>>>
>>> g = globals()
>>> n = 10000
>>> t1 = timeit("var = np.var(a, axis=1, mean=mean)", globals=g, number=n)
>>> t2 = timeit("var = np.var(a, axis=1)", globals=g, number=n)
>>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
#doctest: +SKIP
Percentage execution time saved 32%
vstack = <numpy.ma.extras._fromnxfunction_seq object>
Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays
of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by
`vsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of ndarrays
The arrays must have the same shape along all but the first axis.
1-D arrays must have the same length.
dtype : str or dtype
If provided, the destination array will have this dtype. Cannot be
provided together with `out`.
.. versionadded:: 1.24
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'same_kind'.
.. versionadded:: 1.24
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 2-D.
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
block : Assemble an nd-array from nested lists of blocks.
hstack : Stack arrays in sequence horizontally (column wise).
dstack : Stack arrays in sequence depth wise (along third axis).
column_stack : Stack 1-D arrays as columns into a 2-D array.
vsplit : Split an array into multiple sub-arrays vertically (row-wise).
unstack : Split an array into a tuple of sub-arrays along an axis.
Examples
--------
>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.vstack((a,b))
array([[1, 2, 3],
[4, 5, 6]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[4], [5], [6]])
>>> np.vstack((a,b))
array([[1],
[2],
[3],
[4],
[5],
[6]])
Notes
-----
The function is applied to both the _data and the _mask, if any.
zeros = <numpy.ma.core._convert2ma object>
zeros(shape, dtype=float, order='C', *, like=None)
Return a new array of given shape and type, filled with zeros.
Parameters
----------
shape : int or tuple of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
The desired data-type for the array, e.g., `numpy.int8`. Default is
`numpy.float64`.
order : {'C', 'F'}, optional, default: 'C'
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : MaskedArray
Array of zeros with the given shape, dtype, and order.
See Also
--------
zeros_like : Return an array of zeros with shape and type of input.
empty : Return a new uninitialized array.
ones : Return a new array setting values to one.
full : Return a new array of given shape filled with value.
Examples
--------
>>> import numpy as np
>>> np.zeros(5)
array([ 0., 0., 0., 0., 0.])
>>> np.zeros((5,), dtype=int)
array([0, 0, 0, 0, 0])
>>> np.zeros((2, 1))
array([[ 0.],
[ 0.]])
>>> s = (2,2)
>>> np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])
>>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
array([(0, 0), (0, 0)],
dtype=[('x', '<i4'), ('y', '<i4')])
zeros_like = <numpy.ma.core._convert2ma object>
Return an array of zeros with the same shape and type as a given array.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of
the returned array.
dtype : data-type, optional
Overrides the data type of the result.
.. versionadded:: 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.
.. versionadded:: 1.6.0
subok : bool, 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.
shape : int 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.
.. versionadded:: 1.17.0
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
out : MaskedArray
Array of zeros with the same shape and type as `a`.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
full_like : Return a new array with shape of input filled with value.
zeros : Return a new array setting values to zero.
Examples
--------
>>> import numpy as np
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.zeros_like(x)
array([[0, 0, 0],
[0, 0, 0]])
>>> y = np.arange(3, dtype=float)
>>> y
array([0., 1., 2.])
>>> np.zeros_like(y)
array([0., 0., 0.])
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\ma\__init__.py
numpy.mask_indices
Python Library Documentation: function mask_indices in module numpy
mask_indices(n, mask_func, k=0)
Return the indices to access (n, n) arrays, given a masking function.
Assume `mask_func` is a function that, for a square array a of size
``(n, n)`` with a possible offset argument `k`, when called as
``mask_func(a, k)`` returns a new array with zeros in certain locations
(functions like `triu` or `tril` do precisely this). Then this function
returns the indices where the non-zero values would be located.
Parameters
----------
n : int
The returned indices will be valid to access arrays of shape (n, n).
mask_func : callable
A function whose call signature is similar to that of `triu`, `tril`.
That is, ``mask_func(x, k)`` returns a boolean array, shaped like `x`.
`k` is an optional argument to the function.
k : scalar
An optional argument which is passed through to `mask_func`. Functions
like `triu`, `tril` take a second argument that is interpreted as an
offset.
Returns
-------
indices : tuple of arrays.
The `n` arrays of indices corresponding to the locations where
``mask_func(np.ones((n, n)), k)`` is True.
See Also
--------
triu, tril, triu_indices, tril_indices
Notes
-----
.. versionadded:: 1.4.0
Examples
--------
>>> import numpy as np
These are the indices that would allow you to access the upper triangular
part of any 3x3 array:
>>> iu = np.mask_indices(3, np.triu)
For example, if `a` is a 3x3 array:
>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> a[iu]
array([0, 1, 2, 4, 5, 8])
An offset can be passed also to the masking function. This gets us the
indices starting on the first diagonal right of the main one:
>>> iu1 = np.mask_indices(3, np.triu, 1)
with which we now extract only three elements:
>>> a[iu1]
array([1, 2, 5])
numpy.matmul
Python Library Documentation: ufunc
matmul = <ufunc 'matmul'>
matmul(x1, x2, /, out=None, *, casting='same_kind', order='K', dtype=None, subok=True[, signature, axes, axis])
Matrix product of two arrays.
Parameters
----------
x1, x2 : array_like
Input arrays, scalars not allowed.
out : ndarray, optional
A location into which the result is stored. If provided, it must have
a shape that matches the signature `(n,k),(k,m)->(n,m)`. If not
provided or None, a freshly-allocated array is returned.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
.. versionadded:: 1.16
Now handles ufunc kwargs
Returns
-------
y : ndarray
The matrix product of the inputs.
This is a scalar only when both x1, x2 are 1-d vectors.
Raises
------
ValueError
If the last dimension of `x1` is not the same size as
the second-to-last dimension of `x2`.
If a scalar value is passed in.
See Also
--------
vdot : Complex-conjugating dot product.
tensordot : Sum products over arbitrary axes.
einsum : Einstein summation convention.
dot : alternative matrix product with different broadcasting rules.
Notes
-----
The behavior depends on the arguments in the following way.
- If both arguments are 2-D they are multiplied like conventional
matrices.
- If either argument is N-D, N > 2, it is treated as a stack of
matrices residing in the last two indexes and broadcast accordingly.
- If the first argument is 1-D, it is promoted to a matrix by
prepending a 1 to its dimensions. After matrix multiplication
the prepended 1 is removed.
- If the second argument is 1-D, it is promoted to a matrix by
appending a 1 to its dimensions. After matrix multiplication
the appended 1 is removed.
``matmul`` differs from ``dot`` in two important ways:
- Multiplication by scalars is not allowed, use ``*`` instead.
- Stacks of matrices are broadcast together as if the matrices
were elements, respecting the signature ``(n,k),(k,m)->(n,m)``:
>>> a = np.ones([9, 5, 7, 4])
>>> c = np.ones([9, 5, 4, 3])
>>> np.dot(a, c).shape
(9, 5, 7, 9, 5, 3)
>>> np.matmul(a, c).shape
(9, 5, 7, 3)
>>> # n is 7, k is 4, m is 3
The matmul function implements the semantics of the ``@`` operator
introduced in Python 3.5 following :pep:`465`.
It uses an optimized BLAS library when possible (see `numpy.linalg`).
Examples
--------
For 2-D arrays it is the matrix product:
>>> import numpy as np
>>> a = np.array([[1, 0],
... [0, 1]])
>>> b = np.array([[4, 1],
... [2, 2]])
>>> np.matmul(a, b)
array([[4, 1],
[2, 2]])
For 2-D mixed with 1-D, the result is the usual.
>>> a = np.array([[1, 0],
... [0, 1]])
>>> b = np.array([1, 2])
>>> np.matmul(a, b)
array([1, 2])
>>> np.matmul(b, a)
array([1, 2])
Broadcasting is conventional for stacks of arrays
>>> a = np.arange(2 * 2 * 4).reshape((2, 2, 4))
>>> b = np.arange(2 * 2 * 4).reshape((2, 4, 2))
>>> np.matmul(a,b).shape
(2, 2, 2)
>>> np.matmul(a, b)[0, 1, 1]
98
>>> sum(a[0, 1, :] * b[0 , :, 1])
98
Vector, vector returns the scalar inner product, but neither argument
is complex-conjugated:
>>> np.matmul([2j, 3j], [2j, 3j])
(-13+0j)
Scalar multiplication raises an error.
>>> np.matmul([1,2], 3)
Traceback (most recent call last):
...
ValueError: matmul: Input operand 1 does not have enough dimensions ...
The ``@`` operator can be used as a shorthand for ``np.matmul`` on
ndarrays.
>>> x1 = np.array([2j, 3j])
>>> x2 = np.array([2j, 3j])
>>> x1 @ x2
(-13+0j)
.. versionadded:: 1.10.0
numpy.matrix
Python Library Documentation: class matrix in module numpy
class matrix(ndarray)
| matrix(data, dtype=None, copy=True)
|
| matrix(data, dtype=None, copy=True)
|
| Returns a matrix from an array-like object, or from a string of data.
|
| A matrix is a specialized 2-D array that retains its 2-D nature
| through operations. It has certain special operators, such as ``*``
| (matrix multiplication) and ``**`` (matrix power).
|
| .. note:: It is no longer recommended to use this class, even for linear
| algebra. Instead use regular arrays. The class may be removed
| in the future.
|
| Parameters
| ----------
| data : array_like or string
| If `data` is a string, it is interpreted as a matrix with commas
| or spaces separating columns, and semicolons separating rows.
| dtype : data-type
| Data-type of the output matrix.
| copy : bool
| If `data` is already an `ndarray`, then this flag determines
| whether the data is copied (the default), or whether a view is
| constructed.
|
| See Also
| --------
| array
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.matrix('1 2; 3 4')
| >>> a
| matrix([[1, 2],
| [3, 4]])
|
| >>> np.matrix([[1, 2], [3, 4]])
| matrix([[1, 2],
| [3, 4]])
|
| Method resolution order:
| matrix
| ndarray
| builtins.object
|
| Methods defined here:
|
| __array_finalize__(self, obj) from numpy.matrixlib.defmatrix.matrix
| a.__array_finalize__(obj, /)
|
| Present so subclasses can call super. Does nothing.
|
| __getitem__(self, index) from numpy.matrixlib.defmatrix.matrix
| Return self[key].
|
| __imul__(self, other) from numpy.matrixlib.defmatrix.matrix
| Return self*=value.
|
| __ipow__(self, other) from numpy.matrixlib.defmatrix.matrix
| Return self**=value.
|
| __mul__(self, other) from numpy.matrixlib.defmatrix.matrix
| Return self*value.
|
| __pow__(self, other) from numpy.matrixlib.defmatrix.matrix
| Return pow(self, value, mod).
|
| __rmul__(self, other) from numpy.matrixlib.defmatrix.matrix
| Return value*self.
|
| __rpow__(self, other) from numpy.matrixlib.defmatrix.matrix
| Return pow(value, self, mod).
|
| all(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| Test whether all matrix elements along a given axis evaluate to True.
|
| Parameters
| ----------
| See `numpy.all` for complete descriptions
|
| See Also
| --------
| numpy.all
|
| Notes
| -----
| This is the same as `ndarray.all`, but it returns a `matrix` object.
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> y = x[0]; y
| matrix([[0, 1, 2, 3]])
| >>> (x == y)
| matrix([[ True, True, True, True],
| [False, False, False, False],
| [False, False, False, False]])
| >>> (x == y).all()
| False
| >>> (x == y).all(0)
| matrix([[False, False, False, False]])
| >>> (x == y).all(1)
| matrix([[ True],
| [False],
| [False]])
|
| any(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| Test whether any array element along a given axis evaluates to True.
|
| Refer to `numpy.any` for full documentation.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which logical OR is performed
| out : ndarray, optional
| Output to existing array instead of creating new one, must have
| same shape as expected output
|
| Returns
| -------
| any : bool, ndarray
| Returns a single bool if `axis` is ``None``; otherwise,
| returns `ndarray`
|
| argmax(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| Indexes of the maximum values along an axis.
|
| Return the indexes of the first occurrences of the maximum values
| along the specified axis. If axis is None, the index is for the
| flattened matrix.
|
| Parameters
| ----------
| See `numpy.argmax` for complete descriptions
|
| See Also
| --------
| numpy.argmax
|
| Notes
| -----
| This is the same as `ndarray.argmax`, but returns a `matrix` object
| where `ndarray.argmax` would return an `ndarray`.
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.argmax()
| 11
| >>> x.argmax(0)
| matrix([[2, 2, 2, 2]])
| >>> x.argmax(1)
| matrix([[3],
| [3],
| [3]])
|
| argmin(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| Indexes of the minimum values along an axis.
|
| Return the indexes of the first occurrences of the minimum values
| along the specified axis. If axis is None, the index is for the
| flattened matrix.
|
| Parameters
| ----------
| See `numpy.argmin` for complete descriptions.
|
| See Also
| --------
| numpy.argmin
|
| Notes
| -----
| This is the same as `ndarray.argmin`, but returns a `matrix` object
| where `ndarray.argmin` would return an `ndarray`.
|
| Examples
| --------
| >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, -1, -2, -3],
| [ -4, -5, -6, -7],
| [ -8, -9, -10, -11]])
| >>> x.argmin()
| 11
| >>> x.argmin(0)
| matrix([[2, 2, 2, 2]])
| >>> x.argmin(1)
| matrix([[3],
| [3],
| [3]])
|
| flatten(self, order='C') from numpy.matrixlib.defmatrix.matrix
| Return a flattened copy of the matrix.
|
| All `N` elements of the matrix are placed into a single row.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| 'C' means to flatten in row-major (C-style) order. 'F' means to
| flatten in column-major (Fortran-style) order. 'A' means to
| flatten in column-major order if `m` is Fortran *contiguous* in
| memory, row-major order otherwise. 'K' means to flatten `m` in
| the order the elements occur in memory. The default is 'C'.
|
| Returns
| -------
| y : matrix
| A copy of the matrix, flattened to a `(1, N)` matrix where `N`
| is the number of elements in the original matrix.
|
| See Also
| --------
| ravel : Return a flattened array.
| flat : A 1-D flat iterator over the matrix.
|
| Examples
| --------
| >>> m = np.matrix([[1,2], [3,4]])
| >>> m.flatten()
| matrix([[1, 2, 3, 4]])
| >>> m.flatten('F')
| matrix([[1, 3, 2, 4]])
|
| getA = A(self) from numpy.matrixlib.defmatrix.matrix
| Return `self` as an `ndarray` object.
|
| Equivalent to ``np.asarray(self)``.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| ret : ndarray
| `self` as an `ndarray`
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.getA()
| array([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
|
| getA1 = A1(self) from numpy.matrixlib.defmatrix.matrix
| Return `self` as a flattened `ndarray`.
|
| Equivalent to ``np.asarray(x).ravel()``
|
| Parameters
| ----------
| None
|
| Returns
| -------
| ret : ndarray
| `self`, 1-D, as an `ndarray`
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.getA1()
| array([ 0, 1, 2, ..., 9, 10, 11])
|
| getH = H(self) from numpy.matrixlib.defmatrix.matrix
| Returns the (complex) conjugate transpose of `self`.
|
| Equivalent to ``np.transpose(self)`` if `self` is real-valued.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| ret : matrix object
| complex conjugate transpose of `self`
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4)))
| >>> z = x - 1j*x; z
| matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
| [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
| [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
| >>> z.getH()
| matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
| [ 1. +1.j, 5. +5.j, 9. +9.j],
| [ 2. +2.j, 6. +6.j, 10.+10.j],
| [ 3. +3.j, 7. +7.j, 11.+11.j]])
|
| getI = I(self) from numpy.matrixlib.defmatrix.matrix
| Returns the (multiplicative) inverse of invertible `self`.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| ret : matrix object
| If `self` is non-singular, `ret` is such that ``ret * self`` ==
| ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
| ``True``.
|
| Raises
| ------
| numpy.linalg.LinAlgError: Singular matrix
| If `self` is singular.
|
| See Also
| --------
| linalg.inv
|
| Examples
| --------
| >>> m = np.matrix('[1, 2; 3, 4]'); m
| matrix([[1, 2],
| [3, 4]])
| >>> m.getI()
| matrix([[-2. , 1. ],
| [ 1.5, -0.5]])
| >>> m.getI() * m
| matrix([[ 1., 0.], # may vary
| [ 0., 1.]])
|
| getT = T(self) from numpy.matrixlib.defmatrix.matrix
| Returns the transpose of the matrix.
|
| Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| ret : matrix object
| The (non-conjugated) transpose of the matrix.
|
| See Also
| --------
| transpose, getH
|
| Examples
| --------
| >>> m = np.matrix('[1, 2; 3, 4]')
| >>> m
| matrix([[1, 2],
| [3, 4]])
| >>> m.getT()
| matrix([[1, 3],
| [2, 4]])
|
| max(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| Return the maximum value along an axis.
|
| Parameters
| ----------
| See `amax` for complete descriptions
|
| See Also
| --------
| amax, ndarray.max
|
| Notes
| -----
| This is the same as `ndarray.max`, but returns a `matrix` object
| where `ndarray.max` would return an ndarray.
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.max()
| 11
| >>> x.max(0)
| matrix([[ 8, 9, 10, 11]])
| >>> x.max(1)
| matrix([[ 3],
| [ 7],
| [11]])
|
| mean(self, axis=None, dtype=None, out=None) from numpy.matrixlib.defmatrix.matrix
| Returns the average of the matrix elements along the given axis.
|
| Refer to `numpy.mean` for full documentation.
|
| See Also
| --------
| numpy.mean
|
| Notes
| -----
| Same as `ndarray.mean` except that, where that returns an `ndarray`,
| this returns a `matrix` object.
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3, 4)))
| >>> x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.mean()
| 5.5
| >>> x.mean(0)
| matrix([[4., 5., 6., 7.]])
| >>> x.mean(1)
| matrix([[ 1.5],
| [ 5.5],
| [ 9.5]])
|
| min(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| Return the minimum value along an axis.
|
| Parameters
| ----------
| See `amin` for complete descriptions.
|
| See Also
| --------
| amin, ndarray.min
|
| Notes
| -----
| This is the same as `ndarray.min`, but returns a `matrix` object
| where `ndarray.min` would return an ndarray.
|
| Examples
| --------
| >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, -1, -2, -3],
| [ -4, -5, -6, -7],
| [ -8, -9, -10, -11]])
| >>> x.min()
| -11
| >>> x.min(0)
| matrix([[ -8, -9, -10, -11]])
| >>> x.min(1)
| matrix([[ -3],
| [ -7],
| [-11]])
|
| prod(self, axis=None, dtype=None, out=None) from numpy.matrixlib.defmatrix.matrix
| Return the product of the array elements over the given axis.
|
| Refer to `prod` for full documentation.
|
| See Also
| --------
| prod, ndarray.prod
|
| Notes
| -----
| Same as `ndarray.prod`, except, where that returns an `ndarray`, this
| returns a `matrix` object instead.
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.prod()
| 0
| >>> x.prod(0)
| matrix([[ 0, 45, 120, 231]])
| >>> x.prod(1)
| matrix([[ 0],
| [ 840],
| [7920]])
|
| ptp(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| Peak-to-peak (maximum - minimum) value along the given axis.
|
| Refer to `numpy.ptp` for full documentation.
|
| See Also
| --------
| numpy.ptp
|
| Notes
| -----
| Same as `ndarray.ptp`, except, where that would return an `ndarray` object,
| this returns a `matrix` object.
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.ptp()
| 11
| >>> x.ptp(0)
| matrix([[8, 8, 8, 8]])
| >>> x.ptp(1)
| matrix([[3],
| [3],
| [3]])
|
| ravel(self, order='C') from numpy.matrixlib.defmatrix.matrix
| Return a flattened matrix.
|
| Refer to `numpy.ravel` for more documentation.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| The elements of `m` are read using this index order. 'C' means to
| index the elements in C-like order, with the last axis index
| changing fastest, back to the first axis index changing slowest.
| 'F' means to index the elements in Fortran-like index order, with
| the first index changing fastest, and the last index changing
| slowest. Note that the 'C' and 'F' options take no account of the
| memory layout of the underlying array, and only refer to the order
| of axis indexing. 'A' means to read the elements in Fortran-like
| index order if `m` is Fortran *contiguous* in memory, C-like order
| otherwise. 'K' means to read the elements in the order they occur
| in memory, except for reversing the data when strides are negative.
| By default, 'C' index order is used.
|
| Returns
| -------
| ret : matrix
| Return the matrix flattened to shape `(1, N)` where `N`
| is the number of elements in the original matrix.
| A copy is made only if necessary.
|
| See Also
| --------
| matrix.flatten : returns a similar output matrix but always a copy
| matrix.flat : a flat iterator on the array.
| numpy.ravel : related function which returns an ndarray
|
| squeeze(self, axis=None) from numpy.matrixlib.defmatrix.matrix
| Return a possibly reshaped matrix.
|
| Refer to `numpy.squeeze` for more documentation.
|
| Parameters
| ----------
| axis : None or int or tuple of ints, optional
| Selects a subset of the axes of length one in the shape.
| If an axis is selected with shape entry greater than one,
| an error is raised.
|
| Returns
| -------
| squeezed : matrix
| The matrix, but as a (1, N) matrix if it had shape (N, 1).
|
| See Also
| --------
| numpy.squeeze : related function
|
| Notes
| -----
| If `m` has a single column then that column is returned
| as the single row of a matrix. Otherwise `m` is returned.
| The returned matrix is always either `m` itself or a view into `m`.
| Supplying an axis keyword argument will not affect the returned matrix
| but it may cause an error to be raised.
|
| Examples
| --------
| >>> c = np.matrix([[1], [2]])
| >>> c
| matrix([[1],
| [2]])
| >>> c.squeeze()
| matrix([[1, 2]])
| >>> r = c.T
| >>> r
| matrix([[1, 2]])
| >>> r.squeeze()
| matrix([[1, 2]])
| >>> m = np.matrix([[1, 2], [3, 4]])
| >>> m.squeeze()
| matrix([[1, 2],
| [3, 4]])
|
| std(self, axis=None, dtype=None, out=None, ddof=0) from numpy.matrixlib.defmatrix.matrix
| Return the standard deviation of the array elements along the given axis.
|
| Refer to `numpy.std` for full documentation.
|
| See Also
| --------
| numpy.std
|
| Notes
| -----
| This is the same as `ndarray.std`, except that where an `ndarray` would
| be returned, a `matrix` object is returned instead.
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3, 4)))
| >>> x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.std()
| 3.4520525295346629 # may vary
| >>> x.std(0)
| matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary
| >>> x.std(1)
| matrix([[ 1.11803399],
| [ 1.11803399],
| [ 1.11803399]])
|
| sum(self, axis=None, dtype=None, out=None) from numpy.matrixlib.defmatrix.matrix
| Returns the sum of the matrix elements, along the given axis.
|
| Refer to `numpy.sum` for full documentation.
|
| See Also
| --------
| numpy.sum
|
| Notes
| -----
| This is the same as `ndarray.sum`, except that where an `ndarray` would
| be returned, a `matrix` object is returned instead.
|
| Examples
| --------
| >>> x = np.matrix([[1, 2], [4, 3]])
| >>> x.sum()
| 10
| >>> x.sum(axis=1)
| matrix([[3],
| [7]])
| >>> x.sum(axis=1, dtype='float')
| matrix([[3.],
| [7.]])
| >>> out = np.zeros((2, 1), dtype='float')
| >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out))
| matrix([[3.],
| [7.]])
|
| tolist(self) from numpy.matrixlib.defmatrix.matrix
| Return the matrix as a (possibly nested) list.
|
| See `ndarray.tolist` for full documentation.
|
| See Also
| --------
| ndarray.tolist
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.tolist()
| [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
|
| var(self, axis=None, dtype=None, out=None, ddof=0) from numpy.matrixlib.defmatrix.matrix
| Returns the variance of the matrix elements, along the given axis.
|
| Refer to `numpy.var` for full documentation.
|
| See Also
| --------
| numpy.var
|
| Notes
| -----
| This is the same as `ndarray.var`, except that where an `ndarray` would
| be returned, a `matrix` object is returned instead.
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3, 4)))
| >>> x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.var()
| 11.916666666666666
| >>> x.var(0)
| matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary
| >>> x.var(1)
| matrix([[1.25],
| [1.25],
| [1.25]])
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(subtype, data, dtype=None, copy=True) from numpy.matrixlib.defmatrix.matrix
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| A
| Return `self` as an `ndarray` object.
|
| Equivalent to ``np.asarray(self)``.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| ret : ndarray
| `self` as an `ndarray`
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.getA()
| array([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
|
| A1
| Return `self` as a flattened `ndarray`.
|
| Equivalent to ``np.asarray(x).ravel()``
|
| Parameters
| ----------
| None
|
| Returns
| -------
| ret : ndarray
| `self`, 1-D, as an `ndarray`
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| matrix([[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]])
| >>> x.getA1()
| array([ 0, 1, 2, ..., 9, 10, 11])
|
| H
| Returns the (complex) conjugate transpose of `self`.
|
| Equivalent to ``np.transpose(self)`` if `self` is real-valued.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| ret : matrix object
| complex conjugate transpose of `self`
|
| Examples
| --------
| >>> x = np.matrix(np.arange(12).reshape((3,4)))
| >>> z = x - 1j*x; z
| matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
| [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
| [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
| >>> z.getH()
| matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
| [ 1. +1.j, 5. +5.j, 9. +9.j],
| [ 2. +2.j, 6. +6.j, 10.+10.j],
| [ 3. +3.j, 7. +7.j, 11.+11.j]])
|
| I
| Returns the (multiplicative) inverse of invertible `self`.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| ret : matrix object
| If `self` is non-singular, `ret` is such that ``ret * self`` ==
| ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
| ``True``.
|
| Raises
| ------
| numpy.linalg.LinAlgError: Singular matrix
| If `self` is singular.
|
| See Also
| --------
| linalg.inv
|
| Examples
| --------
| >>> m = np.matrix('[1, 2; 3, 4]'); m
| matrix([[1, 2],
| [3, 4]])
| >>> m.getI()
| matrix([[-2. , 1. ],
| [ 1.5, -0.5]])
| >>> m.getI() * m
| matrix([[ 1., 0.], # may vary
| [ 0., 1.]])
|
| T
| Returns the transpose of the matrix.
|
| Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| ret : matrix object
| The (non-conjugated) transpose of the matrix.
|
| See Also
| --------
| transpose, getH
|
| Examples
| --------
| >>> m = np.matrix('[1, 2; 3, 4]')
| >>> m
| matrix([[1, 2],
| [3, 4]])
| >>> m.getT()
| matrix([[1, 3],
| [2, 4]])
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __array_priority__ = 10.0
|
| ----------------------------------------------------------------------
| Methods inherited from ndarray:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| a.__array__([dtype], *, copy=None)
|
| For ``dtype`` parameter it returns a new reference to self if
| ``dtype`` is not given or it matches array's data type.
| A new array of provided data type is returned if ``dtype``
| is different from the current data type of the array.
| For ``copy`` parameter it returns a new reference to self if
| ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| parameter. The method returns a new array for ``copy=True``, regardless of
| ``dtype`` parameter.
|
| A more detailed explanation of the ``__array__`` interface
| can be found in :ref:`dunder_array.interface`.
|
| __array_function__(...)
|
| __array_namespace__(...)
|
| __array_ufunc__(...)
|
| __array_wrap__(...)
| a.__array_wrap__(array[, context], /)
|
| Returns a view of `array` with the same type as self.
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __complex__(...)
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __copy__(...)
| a.__copy__()
|
| Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
|
| Equivalent to ``a.copy(order='K')``.
|
| __deepcopy__(...)
| a.__deepcopy__(memo, /)
|
| Used if :func:`copy.deepcopy` is called on an array.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __dlpack__(...)
| a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
|
| DLPack Protocol: Part of the Array API.
|
| __dlpack_device__(...)
| a.__dlpack_device__()
|
| DLPack Protocol: Part of the Array API.
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Return self+=value.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __ifloordiv__(self, value, /)
| Return self//=value.
|
| __ilshift__(self, value, /)
| Return self<<=value.
|
| __imatmul__(self, value, /)
| Return self@=value.
|
| __imod__(self, value, /)
| Return self%=value.
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __ior__(self, value, /)
| Return self|=value.
|
| __irshift__(self, value, /)
| Return self>>=value.
|
| __isub__(self, value, /)
| Return self-=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __itruediv__(self, value, /)
| Return self/=value.
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __matmul__(self, value, /)
| Return self@value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| a.__reduce__()
|
| For pickling.
|
| __reduce_ex__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmatmul__(self, value, /)
| Return value@self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __setstate__(...)
| a.__setstate__(state, /)
|
| For unpickling.
|
| The `state` argument must be a sequence that contains the following
| elements:
|
| Parameters
| ----------
| version : int
| optional pickle version. If omitted defaults to 0.
| shape : tuple
| dtype : data-type
| isFortran : bool
| rawdata : string or list
| a binary string with the data (or a list if 'a' is an object array)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| argpartition(...)
| a.argpartition(kth, axis=-1, kind='introselect', order=None)
|
| Returns the indices that would partition this array.
|
| Refer to `numpy.argpartition` for full documentation.
|
| .. versionadded:: 1.8.0
|
| See Also
| --------
| numpy.argpartition : equivalent function
|
| argsort(...)
| a.argsort(axis=-1, kind=None, order=None)
|
| Returns the indices that would sort this array.
|
| Refer to `numpy.argsort` for full documentation.
|
| See Also
| --------
| numpy.argsort : equivalent function
|
| astype(...)
| a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
|
| Copy of the array, cast to a specified type.
|
| Parameters
| ----------
| dtype : str or dtype
| Typecode or data-type to which the array is cast.
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout order of the result.
| '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.
| Default is 'K'.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'unsafe'
| for backwards compatibility.
|
| * '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.
| subok : bool, optional
| If True, then sub-classes will be passed-through (default), otherwise
| the returned array will be forced to be a base-class array.
| copy : bool, optional
| By default, astype always returns a newly allocated array. If this
| is set to false, and the `dtype`, `order`, and `subok`
| requirements are satisfied, the input array is returned instead
| of a copy.
|
| Returns
| -------
| arr_t : ndarray
| Unless `copy` is False and the other conditions for returning the input
| array are satisfied (see description for `copy` input parameter), `arr_t`
| is a new array of the same shape as the input array, with dtype, order
| given by `dtype`, `order`.
|
| Notes
| -----
| .. versionchanged:: 1.17.0
| Casting between a simple data type and a structured one is possible only
| for "unsafe" casting. Casting to multiple fields is allowed, but
| casting from multiple fields is not.
|
| .. versionchanged:: 1.9.0
| Casting from numeric to string types in 'safe' casting mode requires
| that the string dtype length is long enough to store the max
| integer/float value converted.
|
| Raises
| ------
| ComplexWarning
| When casting from complex to float or int. To avoid this,
| one should use ``a.real.astype(t)``.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 2.5])
| >>> x
| array([1. , 2. , 2.5])
|
| >>> x.astype(int)
| array([1, 2, 2])
|
| byteswap(...)
| a.byteswap(inplace=False)
|
| Swap the bytes of the array elements
|
| Toggle between low-endian and big-endian data representation by
| returning a byteswapped array, optionally swapped in-place.
| Arrays of byte-strings are not swapped. The real and imaginary
| parts of a complex number are swapped individually.
|
| Parameters
| ----------
| inplace : bool, optional
| If ``True``, swap bytes in-place, default is ``False``.
|
| Returns
| -------
| out : ndarray
| The byteswapped array. If `inplace` is ``True``, this is
| a view to self.
|
| Examples
| --------
| >>> import numpy as np
| >>> A = np.array([1, 256, 8755], dtype=np.int16)
| >>> list(map(hex, A))
| ['0x1', '0x100', '0x2233']
| >>> A.byteswap(inplace=True)
| array([ 256, 1, 13090], dtype=int16)
| >>> list(map(hex, A))
| ['0x100', '0x1', '0x3322']
|
| Arrays of byte-strings are not swapped
|
| >>> A = np.array([b'ceg', b'fac'])
| >>> A.byteswap()
| array([b'ceg', b'fac'], dtype='|S3')
|
| ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| the same values but different representation in memory
|
| >>> A = np.array([1, 2, 3])
| >>> A.view(np.uint8)
| array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| 0, 0], dtype=uint8)
| >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| array([1, 2, 3])
| >>> A.view(np.uint8)
| array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| 0, 3], dtype=uint8)
|
| choose(...)
| a.choose(choices, out=None, mode='raise')
|
| Use an index array to construct a new array from a set of choices.
|
| Refer to `numpy.choose` for full documentation.
|
| See Also
| --------
| numpy.choose : equivalent function
|
| clip(...)
| a.clip(min=None, max=None, out=None, **kwargs)
|
| Return an array whose values are limited to ``[min, max]``.
| One of max or min must be given.
|
| Refer to `numpy.clip` for full documentation.
|
| See Also
| --------
| numpy.clip : equivalent function
|
| compress(...)
| a.compress(condition, axis=None, out=None)
|
| Return selected slices of this array along given axis.
|
| Refer to `numpy.compress` for full documentation.
|
| See Also
| --------
| numpy.compress : equivalent function
|
| conj(...)
| a.conj()
|
| Complex-conjugate all elements.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| conjugate(...)
| a.conjugate()
|
| Return the complex conjugate, element-wise.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| copy(...)
| a.copy(order='C')
|
| Return a copy of the array.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout of the copy. 'C' means C-order,
| 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| 'C' otherwise. 'K' means match the layout of `a` as closely
| as possible. (Note that this function and :func:`numpy.copy` are very
| similar but have different default values for their order=
| arguments, and this function always passes sub-classes through.)
|
| See also
| --------
| numpy.copy : Similar function with different default behavior
| numpy.copyto
|
| Notes
| -----
| This function is the preferred method for creating an array copy. The
| function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| and will not pass sub-classes through by default.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[1,2,3],[4,5,6]], order='F')
|
| >>> y = x.copy()
|
| >>> x.fill(0)
|
| >>> x
| array([[0, 0, 0],
| [0, 0, 0]])
|
| >>> y
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> y.flags['C_CONTIGUOUS']
| True
|
| For arrays containing Python objects (e.g. dtype=object),
| the copy is a shallow one. The new array will contain the
| same object which may lead to surprises if that object can
| be modified (is mutable):
|
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> b = a.copy()
| >>> b[2][0] = 10
| >>> a
| array([1, 'm', list([10, 3, 4])], dtype=object)
|
| To ensure all elements within an ``object`` array are copied,
| use `copy.deepcopy`:
|
| >>> import copy
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> c = copy.deepcopy(a)
| >>> c[2][0] = 10
| >>> c
| array([1, 'm', list([10, 3, 4])], dtype=object)
| >>> a
| array([1, 'm', list([2, 3, 4])], dtype=object)
|
| cumprod(...)
| a.cumprod(axis=None, dtype=None, out=None)
|
| Return the cumulative product of the elements along the given axis.
|
| Refer to `numpy.cumprod` for full documentation.
|
| See Also
| --------
| numpy.cumprod : equivalent function
|
| cumsum(...)
| a.cumsum(axis=None, dtype=None, out=None)
|
| Return the cumulative sum of the elements along the given axis.
|
| Refer to `numpy.cumsum` for full documentation.
|
| See Also
| --------
| numpy.cumsum : equivalent function
|
| diagonal(...)
| a.diagonal(offset=0, axis1=0, axis2=1)
|
| Return specified diagonals. In NumPy 1.9 the returned array is a
| read-only view instead of a copy as in previous NumPy versions. In
| a future version the read-only restriction will be removed.
|
| Refer to :func:`numpy.diagonal` for full documentation.
|
| See Also
| --------
| numpy.diagonal : equivalent function
|
| dot(...)
|
| dump(...)
| a.dump(file)
|
| Dump a pickle of the array to the specified file.
| The array can be read back with pickle.load or numpy.load.
|
| Parameters
| ----------
| file : str or Path
| A string naming the dump file.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| dumps(...)
| a.dumps()
|
| Returns the pickle of the array as a string.
| pickle.loads will convert the string back to an array.
|
| Parameters
| ----------
| None
|
| fill(...)
| a.fill(value)
|
| Fill the array with a scalar value.
|
| Parameters
| ----------
| value : scalar
| All elements of `a` will be assigned this value.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([1, 2])
| >>> a.fill(0)
| >>> a
| array([0, 0])
| >>> a = np.empty(2)
| >>> a.fill(1)
| >>> a
| array([1., 1.])
|
| Fill expects a scalar value and always behaves the same as assigning
| to a single array element. The following is a rare example where this
| distinction is important:
|
| >>> a = np.array([None, None], dtype=object)
| >>> a[0] = np.array(3)
| >>> a
| array([array(3), None], dtype=object)
| >>> a.fill(np.array(3))
| >>> a
| array([array(3), array(3)], dtype=object)
|
| Where other forms of assignments will unpack the array being assigned:
|
| >>> a[...] = np.array(3)
| >>> a
| array([3, 3], dtype=object)
|
| getfield(...)
| a.getfield(dtype, offset=0)
|
| Returns a field of the given array as a certain type.
|
| A field is a view of the array data with a given data-type. The values in
| the view are determined by the given type and the offset into the current
| array in bytes. The offset needs to be such that the view dtype fits in the
| array dtype; for example an array of dtype complex128 has 16-byte elements.
| If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| between 0 and 12 bytes.
|
| Parameters
| ----------
| dtype : str or dtype
| The data type of the view. The dtype size of the view can not be larger
| than that of the array itself.
| offset : int
| Number of bytes to skip before beginning the element view.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.diag([1.+1.j]*2)
| >>> x[1, 1] = 2 + 4.j
| >>> x
| array([[1.+1.j, 0.+0.j],
| [0.+0.j, 2.+4.j]])
| >>> x.getfield(np.float64)
| array([[1., 0.],
| [0., 2.]])
|
| By choosing an offset of 8 bytes we can select the complex part of the
| array for our view:
|
| >>> x.getfield(np.float64, offset=8)
| array([[1., 0.],
| [0., 4.]])
|
| item(...)
| a.item(*args)
|
| Copy an element of an array to a standard Python scalar and return it.
|
| Parameters
| ----------
| \*args : Arguments (variable number and type)
|
| * none: in this case, the method only works for arrays
| with one element (`a.size == 1`), which element is
| copied into a standard Python scalar object and returned.
|
| * int_type: this argument is interpreted as a flat index into
| the array, specifying which element to copy and return.
|
| * tuple of int_types: functions as does a single int_type argument,
| except that the argument is interpreted as an nd-index into the
| array.
|
| Returns
| -------
| z : Standard Python scalar object
| A copy of the specified element of the array as a suitable
| Python scalar
|
| Notes
| -----
| When the data type of `a` is longdouble or clongdouble, item() returns
| a scalar array object because there is no available Python scalar that
| would not lose information. Void arrays return a buffer object for item(),
| unless fields are defined, in which case a tuple is returned.
|
| `item` is very similar to a[args], except, instead of an array scalar,
| a standard Python scalar is returned. This can be useful for speeding up
| access to elements of the array and doing arithmetic on elements of the
| array using Python's optimized math.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.random.seed(123)
| >>> x = np.random.randint(9, size=(3, 3))
| >>> x
| array([[2, 2, 6],
| [1, 3, 6],
| [1, 0, 1]])
| >>> x.item(3)
| 1
| >>> x.item(7)
| 0
| >>> x.item((0, 1))
| 2
| >>> x.item((2, 2))
| 1
|
| For an array with object dtype, elements are returned as-is.
|
| >>> a = np.array([np.int64(1)], dtype=object)
| >>> a.item() #return np.int64
| np.int64(1)
|
| nonzero(...)
| a.nonzero()
|
| Return the indices of the elements that are non-zero.
|
| Refer to `numpy.nonzero` for full documentation.
|
| See Also
| --------
| numpy.nonzero : equivalent function
|
| partition(...)
| a.partition(kth, axis=-1, kind='introselect', order=None)
|
| Partially sorts the elements in the array 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. In the output array, all elements smaller than the k-th element
| are located to the left of this element and all equal or greater are
| located to its right. The ordering of the elements in the two partitions
| on the either side of the k-th element in the output array is undefined.
|
| .. versionadded:: 1.8.0
|
| Parameters
| ----------
| kth : int or sequence of ints
| Element index to partition by. The kth element value 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 kth it will partition all elements
| indexed by kth of them into their sorted position at once.
|
| .. deprecated:: 1.22.0
| Passing booleans as index is deprecated.
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'introselect'}, optional
| Selection algorithm. Default is 'introselect'.
| order : str 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, and not all fields need to be specified,
| but unspecified fields will still be used, in the order in which
| they come up in the dtype, to break ties.
|
| See Also
| --------
| numpy.partition : Return a partitioned copy of an array.
| argpartition : Indirect partition.
| sort : Full sort.
|
| Notes
| -----
| See ``np.partition`` for notes on the different algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([3, 4, 2, 1])
| >>> a.partition(3)
| >>> a
| array([2, 1, 3, 4]) # may vary
|
| >>> a.partition((1, 3))
| >>> a
| array([1, 2, 3, 4])
|
| put(...)
| a.put(indices, values, mode='raise')
|
| Set ``a.flat[n] = values[n]`` for all `n` in indices.
|
| Refer to `numpy.put` for full documentation.
|
| See Also
| --------
| numpy.put : equivalent function
|
| repeat(...)
| a.repeat(repeats, axis=None)
|
| Repeat elements of an array.
|
| Refer to `numpy.repeat` for full documentation.
|
| See Also
| --------
| numpy.repeat : equivalent function
|
| reshape(...)
| a.reshape(shape, /, *, order='C', copy=None)
|
| Returns an array containing the same data with a new shape.
|
| Refer to `numpy.reshape` for full documentation.
|
| See Also
| --------
| numpy.reshape : equivalent function
|
| Notes
| -----
| Unlike the free function `numpy.reshape`, this method on `ndarray` allows
| the elements of the shape parameter to be passed in as separate arguments.
| For example, ``a.reshape(10, 11)`` is equivalent to
| ``a.reshape((10, 11))``.
|
| resize(...)
| a.resize(new_shape, refcheck=True)
|
| Change shape and size of array in-place.
|
| Parameters
| ----------
| new_shape : tuple of ints, or `n` ints
| Shape of resized array.
| refcheck : bool, optional
| If False, reference count will not be checked. Default is True.
|
| Returns
| -------
| None
|
| Raises
| ------
| ValueError
| If `a` does not own its own data or references or views to it exist,
| and the data memory must be changed.
| PyPy only: will always raise if the data memory must be changed, since
| there is no reliable way to determine if references or views to it
| exist.
|
| SystemError
| If the `order` keyword argument is specified. This behaviour is a
| bug in NumPy.
|
| See Also
| --------
| resize : Return a new array with the specified shape.
|
| Notes
| -----
| This reallocates space for the data area if necessary.
|
| Only contiguous arrays (data elements consecutive in memory) can be
| resized.
|
| The purpose of the reference count check is to make sure you
| do not use this array as a buffer for another Python object and then
| reallocate the memory. However, reference counts can increase in
| other ways so if you are sure that you have not shared the memory
| for this array with another Python object, then you may safely set
| `refcheck` to False.
|
| Examples
| --------
| Shrinking an array: array is flattened (in the order that the data are
| stored in memory), resized, and reshaped:
|
| >>> import numpy as np
|
| >>> a = np.array([[0, 1], [2, 3]], order='C')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [1]])
|
| >>> a = np.array([[0, 1], [2, 3]], order='F')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [2]])
|
| Enlarging an array: as above, but missing entries are filled with zeros:
|
| >>> b = np.array([[0, 1], [2, 3]])
| >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
| >>> b
| array([[0, 1, 2],
| [3, 0, 0]])
|
| Referencing an array prevents resizing...
|
| >>> c = a
| >>> a.resize((1, 1))
| Traceback (most recent call last):
| ...
| ValueError: cannot resize an array that references or is referenced ...
|
| Unless `refcheck` is False:
|
| >>> a.resize((1, 1), refcheck=False)
| >>> a
| array([[0]])
| >>> c
| array([[0]])
|
| round(...)
| a.round(decimals=0, out=None)
|
| Return `a` with each element rounded to the given number of decimals.
|
| Refer to `numpy.around` for full documentation.
|
| See Also
| --------
| numpy.around : equivalent function
|
| searchsorted(...)
| a.searchsorted(v, side='left', sorter=None)
|
| Find indices where elements of v should be inserted in a to maintain order.
|
| For full documentation, see `numpy.searchsorted`
|
| See Also
| --------
| numpy.searchsorted : equivalent function
|
| setfield(...)
| a.setfield(val, dtype, offset=0)
|
| Put a value into a specified place in a field defined by a data-type.
|
| Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| bytes into the field.
|
| Parameters
| ----------
| val : object
| Value to be placed in field.
| dtype : dtype object
| Data-type of the field in which to place `val`.
| offset : int, optional
| The number of bytes into the field at which to place `val`.
|
| Returns
| -------
| None
|
| See Also
| --------
| getfield
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.eye(3)
| >>> x.getfield(np.float64)
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
| >>> x.setfield(3, np.int32)
| >>> x.getfield(np.int32)
| array([[3, 3, 3],
| [3, 3, 3],
| [3, 3, 3]], dtype=int32)
| >>> x
| array([[1.0e+000, 1.5e-323, 1.5e-323],
| [1.5e-323, 1.0e+000, 1.5e-323],
| [1.5e-323, 1.5e-323, 1.0e+000]])
| >>> x.setfield(np.eye(3), np.int32)
| >>> x
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
|
| setflags(...)
| a.setflags(write=None, align=None, uic=None)
|
| Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| respectively.
|
| These Boolean-valued flags affect how numpy interprets the memory
| area used by `a` (see Notes below). The ALIGNED flag can only
| be set to True if the data is actually aligned according to the type.
| The WRITEBACKIFCOPY flag can never be set
| to True. The flag WRITEABLE can only be set to True if the array owns its
| own memory, or the ultimate owner of the memory exposes a writeable buffer
| interface, or is a string. (The exception for string is made so that
| unpickling can be done without copying memory.)
|
| Parameters
| ----------
| write : bool, optional
| Describes whether or not `a` can be written to.
| align : bool, optional
| Describes whether or not `a` is aligned properly for its type.
| uic : bool, optional
| Describes whether or not `a` is a copy of another "base" array.
|
| Notes
| -----
| Array flags provide information about how the memory area used
| for the array is to be interpreted. There are 7 Boolean flags
| in use, only three of which can be changed by the user:
| WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
|
| WRITEABLE (W) the data area can be written to;
|
| ALIGNED (A) the data and strides are aligned appropriately for the hardware
| (as determined by the compiler);
|
| WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| called, the base array will be updated with the contents of this array.
|
| All flags can be accessed using the single (upper case) letter as well
| as the full name.
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.array([[3, 1, 7],
| ... [2, 0, 0],
| ... [8, 5, 9]])
| >>> y
| array([[3, 1, 7],
| [2, 0, 0],
| [8, 5, 9]])
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
| >>> y.setflags(write=0, align=0)
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : False
| ALIGNED : False
| WRITEBACKIFCOPY : False
| >>> y.setflags(uic=1)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: cannot set WRITEBACKIFCOPY flag to True
|
| sort(...)
| a.sort(axis=-1, kind=None, order=None)
|
| Sort an array in-place. Refer to `numpy.sort` for full documentation.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
| and 'mergesort' use timsort under the covers and, in general, the
| actual implementation will vary with datatype. The 'mergesort' option
| is retained for backwards compatibility.
|
| .. versionchanged:: 1.15.0
| The 'stable' option was added.
|
| order : str 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, and 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.
|
| See Also
| --------
| numpy.sort : Return a sorted copy of an array.
| numpy.argsort : Indirect sort.
| numpy.lexsort : Indirect stable sort on multiple keys.
| numpy.searchsorted : Find elements in sorted array.
| numpy.partition: Partial sort.
|
| Notes
| -----
| See `numpy.sort` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,4], [3,1]])
| >>> a.sort(axis=1)
| >>> a
| array([[1, 4],
| [1, 3]])
| >>> a.sort(axis=0)
| >>> a
| array([[1, 3],
| [1, 4]])
|
| Use the `order` keyword to specify a field to use when sorting a
| structured array:
|
| >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
| >>> a.sort(order='y')
| >>> a
| array([(b'c', 1), (b'a', 2)],
| dtype=[('x', 'S1'), ('y', '<i8')])
|
| swapaxes(...)
| a.swapaxes(axis1, axis2)
|
| Return a view of the array with `axis1` and `axis2` interchanged.
|
| Refer to `numpy.swapaxes` for full documentation.
|
| See Also
| --------
| numpy.swapaxes : equivalent function
|
| take(...)
| a.take(indices, axis=None, out=None, mode='raise')
|
| Return an array formed from the elements of `a` at the given indices.
|
| Refer to `numpy.take` for full documentation.
|
| See Also
| --------
| numpy.take : equivalent function
|
| to_device(...)
|
| tobytes(...)
| a.tobytes(order='C')
|
| Construct Python bytes containing the raw data bytes in the array.
|
| Constructs Python bytes showing a copy of the raw contents of
| data memory. The bytes object is produced in C-order by default.
| This behavior is controlled by the ``order`` parameter.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| order : {'C', 'F', 'A'}, optional
| Controls the memory layout of the bytes object. 'C' means C-order,
| 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
| Fortran contiguous, 'C' otherwise. Default is 'C'.
|
| Returns
| -------
| s : bytes
| Python bytes exhibiting a copy of `a`'s raw data.
|
| See also
| --------
| frombuffer
| Inverse of this operation, construct a 1-dimensional array from Python
| bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
| >>> x.tobytes()
| b'\x00\x00\x01\x00\x02\x00\x03\x00'
| >>> x.tobytes('C') == x.tobytes()
| True
| >>> x.tobytes('F')
| b'\x00\x00\x02\x00\x01\x00\x03\x00'
|
| tofile(...)
| a.tofile(fid, sep="", format="%s")
|
| Write array to a file as text or binary (default).
|
| Data is always written in 'C' order, independent of the order of `a`.
| The data produced by this method can be recovered using the function
| fromfile().
|
| Parameters
| ----------
| fid : file or str or Path
| An open file object, or a string containing a filename.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| sep : str
| Separator between array items for text output.
| If "" (empty), a binary file is written, equivalent to
| ``file.write(a.tobytes())``.
| format : str
| Format string for text file output.
| Each entry in the array is formatted to text by first converting
| it to the closest Python type, and then using "format" % item.
|
| Notes
| -----
| This is a convenience function for quick storage of array data.
| Information on endianness and precision is lost, so this method is not a
| good choice for files intended to archive data or transport data between
| machines with different endianness. Some of these problems can be overcome
| by outputting the data as text files, at the expense of speed and file
| size.
|
| When fid is a file object, array contents are directly written to the
| file, bypassing the file object's ``write`` method. As a result, tofile
| cannot be used with files objects supporting compression (e.g., GzipFile)
| or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
|
| tostring(...)
| a.tostring(order='C')
|
| A compatibility alias for `~ndarray.tobytes`, with exactly the same
| behavior.
|
| Despite its name, it returns :class:`bytes` not :class:`str`\ s.
|
| .. deprecated:: 1.19.0
|
| trace(...)
| a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
|
| Return the sum along diagonals of the array.
|
| Refer to `numpy.trace` for full documentation.
|
| See Also
| --------
| numpy.trace : equivalent function
|
| transpose(...)
| a.transpose(*axes)
|
| Returns a view of the array with axes transposed.
|
| Refer to `numpy.transpose` for full documentation.
|
| Parameters
| ----------
| axes : None, tuple of ints, or `n` ints
|
| * None or no argument: reverses the order of the axes.
|
| * tuple of ints: `i` in the `j`-th place in the tuple means that the
| array's `i`-th axis becomes the transposed array's `j`-th axis.
|
| * `n` ints: same as an n-tuple of the same ints (this form is
| intended simply as a "convenience" alternative to the tuple form).
|
| Returns
| -------
| p : ndarray
| View of the array with its axes suitably permuted.
|
| See Also
| --------
| transpose : Equivalent function.
| ndarray.T : Array property returning the array transposed.
| ndarray.reshape : Give a new shape to an array without changing its data.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.transpose()
| array([[1, 3],
| [2, 4]])
| >>> a.transpose((1, 0))
| array([[1, 3],
| [2, 4]])
| >>> a.transpose(1, 0)
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.transpose()
| array([1, 2, 3, 4])
|
| view(...)
| a.view([dtype][, type])
|
| New view of array with the same data.
|
| .. note::
| Passing None for ``dtype`` is different from omitting the parameter,
| since the former invokes ``dtype(None)`` which is an alias for
| ``dtype('float64')``.
|
| Parameters
| ----------
| dtype : data-type or ndarray sub-class, optional
| Data-type descriptor of the returned view, e.g., float32 or int16.
| Omitting it results in the view having the same data-type as `a`.
| This argument can also be specified as an ndarray sub-class, which
| then specifies the type of the returned object (this is equivalent to
| setting the ``type`` parameter).
| type : Python type, optional
| Type of the returned view, e.g., ndarray or matrix. Again, omission
| of the parameter results in type preservation.
|
| Notes
| -----
| ``a.view()`` is used two different ways:
|
| ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| of the array's memory with a different data-type. This can cause a
| reinterpretation of the bytes of memory.
|
| ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| returns an instance of `ndarray_subclass` that looks at the same array
| (same shape, dtype, etc.) This does not cause a reinterpretation of the
| memory.
|
| For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| bytes per entry than the previous dtype (for example, converting a regular
| array to a structured array), then the last axis of ``a`` must be
| contiguous. This axis will be resized in the result.
|
| .. versionchanged:: 1.23.0
| Only the last axis needs to be contiguous. Previously, the entire array
| had to be C-contiguous.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
|
| Viewing array data using a different type and dtype:
|
| >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
| >>> y = x.view(dtype=nonneg, type=np.recarray)
| >>> x["a"]
| array([-1], dtype=int8)
| >>> y.a
| array([255], dtype=uint8)
|
| Creating a view on a structured array so it can be used in calculations
|
| >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
| >>> xv = x.view(dtype=np.int8).reshape(-1,2)
| >>> xv
| array([[1, 2],
| [3, 4]], dtype=int8)
| >>> xv.mean(0)
| array([2., 3.])
|
| Making changes to the view changes the underlying array
|
| >>> xv[0,1] = 20
| >>> x
| array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
|
| Using a view to convert an array to a recarray:
|
| >>> z = x.view(np.recarray)
| >>> z.a
| array([1, 3], dtype=int8)
|
| Views share data:
|
| >>> x[0] = (9, 10)
| >>> z[0]
| np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
|
| Views that change the dtype size (bytes per entry) should normally be
| avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
|
| >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
| >>> y = x[:, ::2]
| >>> y
| array([[1, 3],
| [4, 6]], dtype=int16)
| >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
| Traceback (most recent call last):
| ...
| ValueError: To change to a dtype of a different size, the last axis must be contiguous
| >>> z = y.copy()
| >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
| array([[(1, 3)],
| [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
|
| However, views that change dtype are totally fine for arrays with a
| contiguous last axis, even if the rest of the axes are not C-contiguous:
|
| >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
| >>> x.transpose(1, 0, 2).view(np.int16)
| array([[[ 256, 770],
| [3340, 3854]],
| <BLANKLINE>
| [[1284, 1798],
| [4368, 4882]],
| <BLANKLINE>
| [[2312, 2826],
| [5396, 5910]]], dtype=int16)
|
| ----------------------------------------------------------------------
| Class methods inherited from ndarray:
|
| __class_getitem__(...)
| a.__class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.ndarray` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.ndarray` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.ndarray[Any, np.dtype[Any]]
| numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
| numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ndarray:
|
| __array_interface__
| Array protocol: Python side.
|
| __array_struct__
| Array protocol: C-struct side.
|
| base
| Base object if memory is from some other object.
|
| Examples
| --------
| The base of an array that owns its memory is None:
|
| >>> import numpy as np
| >>> x = np.array([1,2,3,4])
| >>> x.base is None
| True
|
| Slicing creates a view, whose memory is shared with x:
|
| >>> y = x[2:]
| >>> y.base is x
| True
|
| ctypes
| An object to simplify the interaction of the array with the ctypes
| module.
|
| This attribute creates an object that makes it easier to use arrays
| when calling shared libraries with the ctypes module. The returned
| object has, among others, data, shape, and strides attributes (see
| Notes below) which themselves return ctypes objects that can be used
| as arguments to a shared library.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| c : Python object
| Possessing attributes data, shape, strides, etc.
|
| See Also
| --------
| numpy.ctypeslib
|
| Notes
| -----
| Below are the public attributes of this object which were documented
| in "Guide to NumPy" (we have omitted undocumented public attributes,
| as well as documented private attributes):
|
| .. autoattribute:: numpy._core._internal._ctypes.data
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.shape
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.strides
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.data_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.shape_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.strides_as
| :noindex:
|
| If the ctypes module is not available, then the ctypes attribute
| of array objects still returns something useful, but ctypes objects
| are not returned and errors may be raised instead. In particular,
| the object will still have the ``as_parameter`` attribute which will
| return an integer equal to the data attribute.
|
| Examples
| --------
| >>> import numpy as np
| >>> import ctypes
| >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| >>> x
| array([[0, 1],
| [2, 3]], dtype=int32)
| >>> x.ctypes.data
| 31962608 # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| c_uint(0)
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| c_ulong(4294967296)
| >>> x.ctypes.shape
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| >>> x.ctypes.strides
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
|
| data
| Python buffer object pointing to the start of the array's data.
|
| device
|
| dtype
| Data-type of the array's elements.
|
| .. warning::
|
| Setting ``arr.dtype`` is discouraged and may be deprecated in the
| future. Setting will replace the ``dtype`` without modifying the
| memory (see also `ndarray.view` and `ndarray.astype`).
|
| Parameters
| ----------
| None
|
| Returns
| -------
| d : numpy dtype object
|
| See Also
| --------
| ndarray.astype : Cast the values contained in the array to a new data-type.
| ndarray.view : Create a view of the same data but a different data-type.
| numpy.dtype
|
| Examples
| --------
| >>> x
| array([[0, 1],
| [2, 3]])
| >>> x.dtype
| dtype('int32')
| >>> type(x.dtype)
| <type 'numpy.dtype'>
|
| flags
| Information about the memory layout of the array.
|
| Attributes
| ----------
| C_CONTIGUOUS (C)
| The data is in a single, C-style contiguous segment.
| F_CONTIGUOUS (F)
| The data is in a single, Fortran-style contiguous segment.
| OWNDATA (O)
| The array owns the memory it uses or borrows it from another object.
| WRITEABLE (W)
| The data area can be written to. Setting this to False locks
| the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| from its base array at creation time, but a view of a writeable
| array may be subsequently locked while the base array remains writeable.
| (The opposite is not true, in that a view of a locked array may not
| be made writeable. However, currently, locking a base object does not
| lock any views that already reference it, so under that circumstance it
| is possible to alter the contents of a locked array via a previously
| created writeable view onto it.) Attempting to change a non-writeable
| array raises a RuntimeError exception.
| ALIGNED (A)
| The data and all elements are aligned appropriately for the hardware.
| WRITEBACKIFCOPY (X)
| This array is a copy of some other array. The C-API function
| PyArray_ResolveWritebackIfCopy must be called before deallocating
| to the base array will be updated with the contents of this array.
| FNC
| F_CONTIGUOUS and not C_CONTIGUOUS.
| FORC
| F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| BEHAVED (B)
| ALIGNED and WRITEABLE.
| CARRAY (CA)
| BEHAVED and C_CONTIGUOUS.
| FARRAY (FA)
| BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
|
| Notes
| -----
| The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| names are only supported in dictionary access.
|
| Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| changed by the user, via direct assignment to the attribute or dictionary
| entry, or by calling `ndarray.setflags`.
|
| The array flags cannot be set arbitrarily:
|
| - WRITEBACKIFCOPY can only be set ``False``.
| - ALIGNED can only be set ``True`` if the data is truly aligned.
| - WRITEABLE can only be set ``True`` if the array owns its own memory
| or the ultimate owner of the memory exposes a writeable buffer
| interface or is a string.
|
| Arrays can be both C-style and Fortran-style contiguous simultaneously.
| This is clear for 1-dimensional arrays, but can also be true for higher
| dimensional arrays.
|
| Even for contiguous arrays a stride for a given dimension
| ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| or the array has no elements.
| It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| Fortran-style contiguous arrays is true.
|
| flat
| A 1-D iterator over the array.
|
| This is a `numpy.flatiter` instance, which acts similarly to, but is not
| a subclass of, Python's built-in iterator object.
|
| See Also
| --------
| flatten : Return a copy of the array collapsed into one dimension.
|
| flatiter
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(1, 7).reshape(2, 3)
| >>> x
| array([[1, 2, 3],
| [4, 5, 6]])
| >>> x.flat[3]
| 4
| >>> x.T
| array([[1, 4],
| [2, 5],
| [3, 6]])
| >>> x.T.flat[3]
| 5
| >>> type(x.flat)
| <class 'numpy.flatiter'>
|
| An assignment example:
|
| >>> x.flat = 3; x
| array([[3, 3, 3],
| [3, 3, 3]])
| >>> x.flat[[1,4]] = 1; x
| array([[3, 1, 3],
| [3, 1, 3]])
|
| imag
| The imaginary part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.imag
| array([ 0. , 0.70710678])
| >>> x.imag.dtype
| dtype('float64')
|
| itemset
|
| itemsize
| Length of one array element in bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1,2,3], dtype=np.float64)
| >>> x.itemsize
| 8
| >>> x = np.array([1,2,3], dtype=np.complex128)
| >>> x.itemsize
| 16
|
| mT
| View of the matrix transposed array.
|
| The matrix transpose is the transpose of the last two dimensions, even
| if the array is of higher dimension.
|
| .. versionadded:: 2.0
|
| Raises
| ------
| ValueError
| If the array is of dimension less than 2.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.mT
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.arange(8).reshape((2, 2, 2))
| >>> a
| array([[[0, 1],
| [2, 3]],
| <BLANKLINE>
| [[4, 5],
| [6, 7]]])
| >>> a.mT
| array([[[0, 2],
| [1, 3]],
| <BLANKLINE>
| [[4, 6],
| [5, 7]]])
|
| nbytes
| Total bytes consumed by the elements of the array.
|
| Notes
| -----
| Does not include memory consumed by non-element attributes of the
| array object.
|
| See Also
| --------
| sys.getsizeof
| Memory consumed by the object itself without parents in case view.
| This does include memory consumed by non-element attributes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3,5,2), dtype=np.complex128)
| >>> x.nbytes
| 480
| >>> np.prod(x.shape) * x.itemsize
| 480
|
| ndim
| Number of array dimensions.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3])
| >>> x.ndim
| 1
| >>> y = np.zeros((2, 3, 4))
| >>> y.ndim
| 3
|
| newbyteorder
|
| real
| The real part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.real
| array([ 1. , 0.70710678])
| >>> x.real.dtype
| dtype('float64')
|
| See Also
| --------
| numpy.real : equivalent function
|
| shape
| Tuple of array dimensions.
|
| The shape property is usually used to get the current shape of an array,
| but may also be used to reshape the array in-place by assigning a tuple of
| array dimensions to it. As with `numpy.reshape`, one of the new shape
| dimensions can be -1, in which case its value is inferred from the size of
| the array and the remaining dimensions. Reshaping an array in-place will
| fail if a copy is required.
|
| .. warning::
|
| Setting ``arr.shape`` is discouraged and may be deprecated in the
| future. Using `ndarray.reshape` is the preferred approach.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3, 4])
| >>> x.shape
| (4,)
| >>> y = np.zeros((2, 3, 4))
| >>> y.shape
| (2, 3, 4)
| >>> y.shape = (3, 8)
| >>> y
| array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| >>> y.shape = (3, 6)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: total size of new array must be unchanged
| >>> np.zeros((4,2))[::2].shape = (-1,)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| AttributeError: Incompatible shape for in-place modification. Use
| `.reshape()` to make a copy with the desired shape.
|
| See Also
| --------
| numpy.shape : Equivalent getter function.
| numpy.reshape : Function similar to setting ``shape``.
| ndarray.reshape : Method similar to setting ``shape``.
|
| size
| Number of elements in the array.
|
| Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| dimensions.
|
| Notes
| -----
| `a.size` returns a standard arbitrary precision Python integer. This
| may not be the case with other methods of obtaining the same value
| (like the suggested ``np.prod(a.shape)``, which returns an instance
| of ``np.int_``), and may be relevant if the value is used further in
| calculations that may overflow a fixed size integer type.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| >>> x.size
| 30
| >>> np.prod(x.shape)
| 30
|
| strides
| Tuple of bytes to step in each dimension when traversing an array.
|
| The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| is::
|
| offset = sum(np.array(i) * a.strides)
|
| A more detailed explanation of strides can be found in
| :ref:`arrays.ndarray`.
|
| .. warning::
|
| Setting ``arr.strides`` is discouraged and may be deprecated in the
| future. `numpy.lib.stride_tricks.as_strided` should be preferred
| to create a new view of the same data in a safer way.
|
| Notes
| -----
| Imagine an array of 32-bit integers (each 4 bytes)::
|
| x = np.array([[0, 1, 2, 3, 4],
| [5, 6, 7, 8, 9]], dtype=np.int32)
|
| This array is stored in memory as 40 bytes, one after the other
| (known as a contiguous block of memory). The strides of an array tell
| us how many bytes we have to skip in memory to move to the next position
| along a certain axis. For example, we have to skip 4 bytes (1 value) to
| move to the next column, but 20 bytes (5 values) to get to the same
| position in the next row. As such, the strides for the array `x` will be
| ``(20, 4)``.
|
| See Also
| --------
| numpy.lib.stride_tricks.as_strided
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| >>> y
| array([[[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]],
| [[12, 13, 14, 15],
| [16, 17, 18, 19],
| [20, 21, 22, 23]]])
| >>> y.strides
| (48, 16, 4)
| >>> y[1,1,1]
| 17
| >>> offset=sum(y.strides * np.array((1,1,1)))
| >>> offset/y.itemsize
| 17
|
| >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| >>> x.strides
| (32, 4, 224, 1344)
| >>> i = np.array([3,5,2,2])
| >>> offset = sum(i * x.strides)
| >>> x[3,5,2,2]
| 813
| >>> offset / x.itemsize
| 813
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from ndarray:
|
| __hash__ = None
numpy.matrix_transpose
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
matrix_transpose(x, /)
Transposes a matrix (or a stack of matrices) ``x``.
This function is Array API compatible.
Parameters
----------
x : array_like
Input array having shape (..., M, N) and whose two innermost
dimensions form ``MxN`` matrices.
Returns
-------
out : ndarray
An array containing the transpose for each matrix and having shape
(..., N, M).
See Also
--------
transpose : Generic transpose method.
Examples
--------
>>> import numpy as np
>>> np.matrix_transpose([[1, 2], [3, 4]])
array([[1, 3],
[2, 4]])
>>> np.matrix_transpose([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
array([[[1, 3],
[2, 4]],
[[5, 7],
[6, 8]]])
numpy.max
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
max(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the maximum of an array or maximum along an axis.
Parameters
----------
a : array_like
Input data.
axis : None or int or tuple of ints, optional
Axis or axes along which to operate. By default, flattened input is
used.
.. versionadded:: 1.7.0
If this is a tuple of ints, the maximum is selected over multiple axes,
instead of a single axis or all the axes as before.
out : ndarray, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
See :ref:`ufuncs-output-type` for more details.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the ``max`` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
initial : scalar, optional
The minimum value of an output element. Must be present to allow
computation on empty slice. See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.15.0
where : array_like of bool, optional
Elements to compare for the maximum. See `~numpy.ufunc.reduce`
for details.
.. versionadded:: 1.17.0
Returns
-------
max : ndarray or scalar
Maximum of `a`. If `axis` is None, the result is a scalar value.
If `axis` is an int, the result is an array of dimension
``a.ndim - 1``. If `axis` is a tuple, the result is an array of
dimension ``a.ndim - len(axis)``.
See Also
--------
amin :
The minimum value of an array along a given axis, propagating any NaNs.
nanmax :
The maximum value of an array along a given axis, ignoring any NaNs.
maximum :
Element-wise maximum of two arrays, propagating any NaNs.
fmax :
Element-wise maximum of two arrays, ignoring any NaNs.
argmax :
Return the indices of the maximum values.
nanmin, minimum, fmin
Notes
-----
NaN values are propagated, that is if at least one item is NaN, the
corresponding max value will be NaN as well. To ignore NaN values
(MATLAB behavior), please use nanmax.
Don't use `~numpy.max` for element-wise comparison of 2 arrays; when
``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
``max(a, axis=0)``.
Examples
--------
>>> import numpy as np
>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
[2, 3]])
>>> np.max(a) # Maximum of the flattened array
3
>>> np.max(a, axis=0) # Maxima along the first axis
array([2, 3])
>>> np.max(a, axis=1) # Maxima along the second axis
array([1, 3])
>>> np.max(a, where=[False, True], initial=-1, axis=0)
array([-1, 3])
>>> b = np.arange(5, dtype=float)
>>> b[2] = np.nan
>>> np.max(b)
np.float64(nan)
>>> np.max(b, where=~np.isnan(b), initial=-1)
4.0
>>> np.nanmax(b)
4.0
You can use an initial value to compute the maximum of an empty slice, or
to initialize it to a different value:
>>> np.max([[-50], [10]], axis=-1, initial=0)
array([ 0, 10])
Notice that the initial value is used as one of the elements for which the
maximum is determined, unlike for the default argument Python's max
function, which is only used for empty iterables.
>>> np.max([5], initial=6)
6
>>> max([5], default=6)
5
numpy.maximum
Python Library Documentation: ufunc
maximum = <ufunc 'maximum'>
maximum(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Element-wise maximum of array elements.
Compare two arrays and return a new array containing the element-wise
maxima. If one of the elements being compared is a NaN, then that
element is returned. If both elements are NaNs then the first is
returned. The latter distinction is important for complex NaNs, which
are defined as at least one of the real or imaginary parts being a NaN.
The net effect is that NaNs are propagated.
Parameters
----------
x1, x2 : array_like
The arrays holding the elements to be compared.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The maximum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
minimum :
Element-wise minimum of two arrays, propagates NaNs.
fmax :
Element-wise maximum of two arrays, ignores NaNs.
amax :
The maximum value of an array along a given axis, propagates NaNs.
nanmax :
The maximum value of an array along a given axis, ignores NaNs.
fmin, amin, nanmin
Notes
-----
The maximum is equivalent to ``np.where(x1 >= x2, x1, x2)`` when
neither x1 nor x2 are nans, but it is faster and does proper
broadcasting.
Examples
--------
>>> import numpy as np
>>> np.maximum([2, 3, 4], [1, 5, 2])
array([2, 5, 4])
>>> np.maximum(np.eye(2), [0.5, 2]) # broadcasting
array([[ 1. , 2. ],
[ 0.5, 2. ]])
>>> np.maximum([np.nan, 0, np.nan], [0, np.nan, np.nan])
array([nan, nan, nan])
>>> np.maximum(np.inf, 1)
inf
numpy.mean
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
mean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>)
Compute the arithmetic mean along the specified axis.
Returns the average of the array elements. The average is taken over
the flattened array by default, otherwise over the specified axis.
`float64` intermediate and return values are used for integer inputs.
Parameters
----------
a : array_like
Array containing numbers whose mean is desired. If `a` is not an
array, a conversion is attempted.
axis : None or int or tuple of ints, optional
Axis or axes along which the means are computed. The default is to
compute the mean of the flattened array.
.. versionadded:: 1.7.0
If this is a tuple of ints, a mean is performed over multiple axes,
instead of a single axis or all the axes as before.
dtype : data-type, optional
Type to use in computing the mean. For integer inputs, the default
is `float64`; for floating point inputs, it is the same as the
input dtype.
out : ndarray, 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 :ref:`ufuncs-output-type` for more details.
See :ref:`ufuncs-output-type` for more details.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `mean` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
where : array_like of bool, optional
Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.20.0
Returns
-------
m : ndarray, see dtype parameter above
If `out=None`, returns a new array containing the mean values,
otherwise a reference to the output array is returned.
See Also
--------
average : Weighted average
std, var, nanmean, nanstd, nanvar
Notes
-----
The arithmetic mean is the sum of the elements along the axis divided
by the number of elements.
Note that for floating-point input, the mean 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-precision accumulator using the
`dtype` keyword can alleviate this issue.
By default, `float16` results are computed using `float32` intermediates
for extra precision.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a)
2.5
>>> np.mean(a, axis=0)
array([2., 3.])
>>> np.mean(a, axis=1)
array([1.5, 3.5])
In single precision, `mean` can be inaccurate:
>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.mean(a)
0.54999924
Computing the mean in float64 is more accurate:
>>> np.mean(a, dtype=np.float64)
0.55000000074505806 # may vary
Specifying a where argument:
>>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
>>> np.mean(a)
12.0
>>> np.mean(a, where=[[True], [False], [False]])
9.0
numpy.median
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
median(a, axis=None, out=None, overwrite_input=False, keepdims=False)
Compute the median along the specified axis.
Returns the median of the array elements.
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : {int, sequence of int, None}, optional
Axis or axes along which the medians are computed. The default,
axis=None, will compute the median along a flattened version of
the array.
.. versionadded:: 1.9.0
If a sequence of axes, the array is first flattened along the
given axes, then the median is computed along the resulting
flattened axis.
out : ndarray, 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_input : bool, optional
If True, then allow use of memory of input array `a` for
calculations. The input array will be modified by the call to
`median`. This will save memory when you do not need to preserve
the contents of the input array. Treat the input as undefined,
but it will probably be fully or partially sorted. Default is
False. If `overwrite_input` is ``True`` and `a` is not already an
`ndarray`, an error will be raised.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `arr`.
.. versionadded:: 1.9.0
Returns
-------
median : ndarray
A new array holding the result. If the input contains integers
or floats smaller than ``float64``, then the output data-type is
``np.float64``. Otherwise, the data-type of the output is the
same as that of the input. If `out` is specified, that array is
returned instead.
See Also
--------
mean, percentile
Notes
-----
Given a vector ``V`` of length ``N``, the median of ``V`` is the
middle value of a sorted copy of ``V``, ``V_sorted`` - i
e., ``V_sorted[(N-1)/2]``, when ``N`` is odd, and the average of the
two middle values of ``V_sorted`` when ``N`` is even.
Examples
--------
>>> import numpy as np
>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10, 7, 4],
[ 3, 2, 1]])
>>> np.median(a)
np.float64(3.5)
>>> np.median(a, axis=0)
array([6.5, 4.5, 2.5])
>>> np.median(a, axis=1)
array([7., 2.])
>>> np.median(a, axis=(0, 1))
np.float64(3.5)
>>> m = np.median(a, axis=0)
>>> out = np.zeros_like(m)
>>> np.median(a, axis=0, out=m)
array([6.5, 4.5, 2.5])
>>> m
array([6.5, 4.5, 2.5])
>>> b = a.copy()
>>> np.median(b, axis=1, overwrite_input=True)
array([7., 2.])
>>> assert not np.all(a==b)
>>> b = a.copy()
>>> np.median(b, axis=None, overwrite_input=True)
np.float64(3.5)
>>> assert not np.all(a==b)
numpy.memmap
Python Library Documentation: class memmap in module numpy
class memmap(ndarray)
| memmap(filename, dtype=<class 'numpy.uint8'>, mode='r+', offset=0, shape=None, order='C')
|
| Create a memory-map to an array stored in a *binary* file on disk.
|
| Memory-mapped files are used for accessing small segments of large files
| on disk, without reading the entire file into memory. NumPy's
| memmap's are array-like objects. This differs from Python's ``mmap``
| module, which uses file-like objects.
|
| This subclass of ndarray has some unpleasant interactions with
| some operations, because it doesn't quite fit properly as a subclass.
| An alternative to using this subclass is to create the ``mmap``
| object yourself, then create an ndarray with ndarray.__new__ directly,
| passing the object created in its 'buffer=' parameter.
|
| This class may at some point be turned into a factory function
| which returns a view into an mmap buffer.
|
| Flush the memmap instance to write the changes to the file. Currently there
| is no API to close the underlying ``mmap``. It is tricky to ensure the
| resource is actually closed, since it may be shared between different
| memmap instances.
|
|
| Parameters
| ----------
| filename : str, file-like object, or pathlib.Path instance
| The file name or file object to be used as the array data buffer.
| dtype : data-type, optional
| The data-type used to interpret the file contents.
| Default is `uint8`.
| mode : {'r+', 'r', 'w+', 'c'}, optional
| The file is opened in this mode:
|
| +------+-------------------------------------------------------------+
| | 'r' | Open existing file for reading only. |
| +------+-------------------------------------------------------------+
| | 'r+' | Open existing file for reading and writing. |
| +------+-------------------------------------------------------------+
| | 'w+' | Create or overwrite existing file for reading and writing. |
| | | If ``mode == 'w+'`` then `shape` must also be specified. |
| +------+-------------------------------------------------------------+
| | 'c' | Copy-on-write: assignments affect data in memory, but |
| | | changes are not saved to disk. The file on disk is |
| | | read-only. |
| +------+-------------------------------------------------------------+
|
| Default is 'r+'.
| offset : int, optional
| In the file, array data starts at this offset. Since `offset` is
| measured in bytes, it should normally be a multiple of the byte-size
| of `dtype`. When ``mode != 'r'``, even positive offsets beyond end of
| file are valid; The file will be extended to accommodate the
| additional data. By default, ``memmap`` will start at the beginning of
| the file, even if ``filename`` is a file pointer ``fp`` and
| ``fp.tell() != 0``.
| shape : int or sequence of ints, optional
| The desired shape of the array. If ``mode == 'r'`` and the number
| of remaining bytes after `offset` is not a multiple of the byte-size
| of `dtype`, you must specify `shape`. By default, the returned array
| will be 1-D with the number of elements determined by file size
| and data-type.
|
| .. versionchanged:: 2.0
| The shape parameter can now be any integer sequence type, previously
| types were limited to tuple and int.
|
| order : {'C', 'F'}, optional
| Specify the order of the ndarray memory layout:
| :term:`row-major`, C-style or :term:`column-major`,
| Fortran-style. This only has an effect if the shape is
| greater than 1-D. The default order is 'C'.
|
| Attributes
| ----------
| filename : str or pathlib.Path instance
| Path to the mapped file.
| offset : int
| Offset position in the file.
| mode : str
| File mode.
|
| Methods
| -------
| flush
| Flush any changes in memory to file on disk.
| When you delete a memmap object, flush is called first to write
| changes to disk.
|
|
| See also
| --------
| lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file.
|
| Notes
| -----
| The memmap object can be used anywhere an ndarray is accepted.
| Given a memmap ``fp``, ``isinstance(fp, numpy.ndarray)`` returns
| ``True``.
|
| Memory-mapped files cannot be larger than 2GB on 32-bit systems.
|
| When a memmap causes a file to be created or extended beyond its
| current size in the filesystem, the contents of the new part are
| unspecified. On systems with POSIX filesystem semantics, the extended
| part will be filled with zero bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> data = np.arange(12, dtype='float32')
| >>> data.resize((3,4))
|
| This example uses a temporary file so that doctest doesn't write
| files to your directory. You would use a 'normal' filename.
|
| >>> from tempfile import mkdtemp
| >>> import os.path as path
| >>> filename = path.join(mkdtemp(), 'newfile.dat')
|
| Create a memmap with dtype and shape that matches our data:
|
| >>> fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))
| >>> fp
| memmap([[0., 0., 0., 0.],
| [0., 0., 0., 0.],
| [0., 0., 0., 0.]], dtype=float32)
|
| Write data to memmap array:
|
| >>> fp[:] = data[:]
| >>> fp
| memmap([[ 0., 1., 2., 3.],
| [ 4., 5., 6., 7.],
| [ 8., 9., 10., 11.]], dtype=float32)
|
| >>> fp.filename == path.abspath(filename)
| True
|
| Flushes memory changes to disk in order to read them back
|
| >>> fp.flush()
|
| Load the memmap and verify data was stored:
|
| >>> newfp = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
| >>> newfp
| memmap([[ 0., 1., 2., 3.],
| [ 4., 5., 6., 7.],
| [ 8., 9., 10., 11.]], dtype=float32)
|
| Read-only memmap:
|
| >>> fpr = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
| >>> fpr.flags.writeable
| False
|
| Copy-on-write memmap:
|
| >>> fpc = np.memmap(filename, dtype='float32', mode='c', shape=(3,4))
| >>> fpc.flags.writeable
| True
|
| It's possible to assign to copy-on-write array, but values are only
| written into the memory copy of the array, and not written to disk:
|
| >>> fpc
| memmap([[ 0., 1., 2., 3.],
| [ 4., 5., 6., 7.],
| [ 8., 9., 10., 11.]], dtype=float32)
| >>> fpc[0,:] = 0
| >>> fpc
| memmap([[ 0., 0., 0., 0.],
| [ 4., 5., 6., 7.],
| [ 8., 9., 10., 11.]], dtype=float32)
|
| File on disk is unchanged:
|
| >>> fpr
| memmap([[ 0., 1., 2., 3.],
| [ 4., 5., 6., 7.],
| [ 8., 9., 10., 11.]], dtype=float32)
|
| Offset into a memmap:
|
| >>> fpo = np.memmap(filename, dtype='float32', mode='r', offset=16)
| >>> fpo
| memmap([ 4., 5., 6., 7., 8., 9., 10., 11.], dtype=float32)
|
| Method resolution order:
| memmap
| ndarray
| builtins.object
|
| Methods defined here:
|
| __array_finalize__(self, obj) from numpy._core.memmap.memmap
| a.__array_finalize__(obj, /)
|
| Present so subclasses can call super. Does nothing.
|
| __array_wrap__(self, arr, context=None, return_scalar=False) from numpy._core.memmap.memmap
| a.__array_wrap__(array[, context], /)
|
| Returns a view of `array` with the same type as self.
|
| __getitem__(self, index) from numpy._core.memmap.memmap
| Return self[key].
|
| flush(self) from numpy._core.memmap.memmap
| Write any changes in the array to the file on disk.
|
| For further information, see `memmap`.
|
| Parameters
| ----------
| None
|
| See Also
| --------
| memmap
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(subtype, filename, dtype=<class 'numpy.uint8'>, mode='r+', offset=0, shape=None, order='C') from numpy._core.memmap.memmap
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __array_priority__ = -100.0
|
| ----------------------------------------------------------------------
| Methods inherited from ndarray:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| a.__array__([dtype], *, copy=None)
|
| For ``dtype`` parameter it returns a new reference to self if
| ``dtype`` is not given or it matches array's data type.
| A new array of provided data type is returned if ``dtype``
| is different from the current data type of the array.
| For ``copy`` parameter it returns a new reference to self if
| ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| parameter. The method returns a new array for ``copy=True``, regardless of
| ``dtype`` parameter.
|
| A more detailed explanation of the ``__array__`` interface
| can be found in :ref:`dunder_array.interface`.
|
| __array_function__(...)
|
| __array_namespace__(...)
|
| __array_ufunc__(...)
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __complex__(...)
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __copy__(...)
| a.__copy__()
|
| Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
|
| Equivalent to ``a.copy(order='K')``.
|
| __deepcopy__(...)
| a.__deepcopy__(memo, /)
|
| Used if :func:`copy.deepcopy` is called on an array.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __dlpack__(...)
| a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
|
| DLPack Protocol: Part of the Array API.
|
| __dlpack_device__(...)
| a.__dlpack_device__()
|
| DLPack Protocol: Part of the Array API.
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Return self+=value.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __ifloordiv__(self, value, /)
| Return self//=value.
|
| __ilshift__(self, value, /)
| Return self<<=value.
|
| __imatmul__(self, value, /)
| Return self@=value.
|
| __imod__(self, value, /)
| Return self%=value.
|
| __imul__(self, value, /)
| Return self*=value.
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __ior__(self, value, /)
| Return self|=value.
|
| __ipow__(self, value, /)
| Return self**=value.
|
| __irshift__(self, value, /)
| Return self>>=value.
|
| __isub__(self, value, /)
| Return self-=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __itruediv__(self, value, /)
| Return self/=value.
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __matmul__(self, value, /)
| Return self@value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| a.__reduce__()
|
| For pickling.
|
| __reduce_ex__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmatmul__(self, value, /)
| Return value@self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __setstate__(...)
| a.__setstate__(state, /)
|
| For unpickling.
|
| The `state` argument must be a sequence that contains the following
| elements:
|
| Parameters
| ----------
| version : int
| optional pickle version. If omitted defaults to 0.
| shape : tuple
| dtype : data-type
| isFortran : bool
| rawdata : string or list
| a binary string with the data (or a list if 'a' is an object array)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| a.all(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if all elements evaluate to True.
|
| Refer to `numpy.all` for full documentation.
|
| See Also
| --------
| numpy.all : equivalent function
|
| any(...)
| a.any(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if any of the elements of `a` evaluate to True.
|
| Refer to `numpy.any` for full documentation.
|
| See Also
| --------
| numpy.any : equivalent function
|
| argmax(...)
| a.argmax(axis=None, out=None, *, keepdims=False)
|
| Return indices of the maximum values along the given axis.
|
| Refer to `numpy.argmax` for full documentation.
|
| See Also
| --------
| numpy.argmax : equivalent function
|
| argmin(...)
| a.argmin(axis=None, out=None, *, keepdims=False)
|
| Return indices of the minimum values along the given axis.
|
| Refer to `numpy.argmin` for detailed documentation.
|
| See Also
| --------
| numpy.argmin : equivalent function
|
| argpartition(...)
| a.argpartition(kth, axis=-1, kind='introselect', order=None)
|
| Returns the indices that would partition this array.
|
| Refer to `numpy.argpartition` for full documentation.
|
| .. versionadded:: 1.8.0
|
| See Also
| --------
| numpy.argpartition : equivalent function
|
| argsort(...)
| a.argsort(axis=-1, kind=None, order=None)
|
| Returns the indices that would sort this array.
|
| Refer to `numpy.argsort` for full documentation.
|
| See Also
| --------
| numpy.argsort : equivalent function
|
| astype(...)
| a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
|
| Copy of the array, cast to a specified type.
|
| Parameters
| ----------
| dtype : str or dtype
| Typecode or data-type to which the array is cast.
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout order of the result.
| '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.
| Default is 'K'.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'unsafe'
| for backwards compatibility.
|
| * '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.
| subok : bool, optional
| If True, then sub-classes will be passed-through (default), otherwise
| the returned array will be forced to be a base-class array.
| copy : bool, optional
| By default, astype always returns a newly allocated array. If this
| is set to false, and the `dtype`, `order`, and `subok`
| requirements are satisfied, the input array is returned instead
| of a copy.
|
| Returns
| -------
| arr_t : ndarray
| Unless `copy` is False and the other conditions for returning the input
| array are satisfied (see description for `copy` input parameter), `arr_t`
| is a new array of the same shape as the input array, with dtype, order
| given by `dtype`, `order`.
|
| Notes
| -----
| .. versionchanged:: 1.17.0
| Casting between a simple data type and a structured one is possible only
| for "unsafe" casting. Casting to multiple fields is allowed, but
| casting from multiple fields is not.
|
| .. versionchanged:: 1.9.0
| Casting from numeric to string types in 'safe' casting mode requires
| that the string dtype length is long enough to store the max
| integer/float value converted.
|
| Raises
| ------
| ComplexWarning
| When casting from complex to float or int. To avoid this,
| one should use ``a.real.astype(t)``.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 2.5])
| >>> x
| array([1. , 2. , 2.5])
|
| >>> x.astype(int)
| array([1, 2, 2])
|
| byteswap(...)
| a.byteswap(inplace=False)
|
| Swap the bytes of the array elements
|
| Toggle between low-endian and big-endian data representation by
| returning a byteswapped array, optionally swapped in-place.
| Arrays of byte-strings are not swapped. The real and imaginary
| parts of a complex number are swapped individually.
|
| Parameters
| ----------
| inplace : bool, optional
| If ``True``, swap bytes in-place, default is ``False``.
|
| Returns
| -------
| out : ndarray
| The byteswapped array. If `inplace` is ``True``, this is
| a view to self.
|
| Examples
| --------
| >>> import numpy as np
| >>> A = np.array([1, 256, 8755], dtype=np.int16)
| >>> list(map(hex, A))
| ['0x1', '0x100', '0x2233']
| >>> A.byteswap(inplace=True)
| array([ 256, 1, 13090], dtype=int16)
| >>> list(map(hex, A))
| ['0x100', '0x1', '0x3322']
|
| Arrays of byte-strings are not swapped
|
| >>> A = np.array([b'ceg', b'fac'])
| >>> A.byteswap()
| array([b'ceg', b'fac'], dtype='|S3')
|
| ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| the same values but different representation in memory
|
| >>> A = np.array([1, 2, 3])
| >>> A.view(np.uint8)
| array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| 0, 0], dtype=uint8)
| >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| array([1, 2, 3])
| >>> A.view(np.uint8)
| array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| 0, 3], dtype=uint8)
|
| choose(...)
| a.choose(choices, out=None, mode='raise')
|
| Use an index array to construct a new array from a set of choices.
|
| Refer to `numpy.choose` for full documentation.
|
| See Also
| --------
| numpy.choose : equivalent function
|
| clip(...)
| a.clip(min=None, max=None, out=None, **kwargs)
|
| Return an array whose values are limited to ``[min, max]``.
| One of max or min must be given.
|
| Refer to `numpy.clip` for full documentation.
|
| See Also
| --------
| numpy.clip : equivalent function
|
| compress(...)
| a.compress(condition, axis=None, out=None)
|
| Return selected slices of this array along given axis.
|
| Refer to `numpy.compress` for full documentation.
|
| See Also
| --------
| numpy.compress : equivalent function
|
| conj(...)
| a.conj()
|
| Complex-conjugate all elements.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| conjugate(...)
| a.conjugate()
|
| Return the complex conjugate, element-wise.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| copy(...)
| a.copy(order='C')
|
| Return a copy of the array.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout of the copy. 'C' means C-order,
| 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| 'C' otherwise. 'K' means match the layout of `a` as closely
| as possible. (Note that this function and :func:`numpy.copy` are very
| similar but have different default values for their order=
| arguments, and this function always passes sub-classes through.)
|
| See also
| --------
| numpy.copy : Similar function with different default behavior
| numpy.copyto
|
| Notes
| -----
| This function is the preferred method for creating an array copy. The
| function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| and will not pass sub-classes through by default.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[1,2,3],[4,5,6]], order='F')
|
| >>> y = x.copy()
|
| >>> x.fill(0)
|
| >>> x
| array([[0, 0, 0],
| [0, 0, 0]])
|
| >>> y
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> y.flags['C_CONTIGUOUS']
| True
|
| For arrays containing Python objects (e.g. dtype=object),
| the copy is a shallow one. The new array will contain the
| same object which may lead to surprises if that object can
| be modified (is mutable):
|
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> b = a.copy()
| >>> b[2][0] = 10
| >>> a
| array([1, 'm', list([10, 3, 4])], dtype=object)
|
| To ensure all elements within an ``object`` array are copied,
| use `copy.deepcopy`:
|
| >>> import copy
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> c = copy.deepcopy(a)
| >>> c[2][0] = 10
| >>> c
| array([1, 'm', list([10, 3, 4])], dtype=object)
| >>> a
| array([1, 'm', list([2, 3, 4])], dtype=object)
|
| cumprod(...)
| a.cumprod(axis=None, dtype=None, out=None)
|
| Return the cumulative product of the elements along the given axis.
|
| Refer to `numpy.cumprod` for full documentation.
|
| See Also
| --------
| numpy.cumprod : equivalent function
|
| cumsum(...)
| a.cumsum(axis=None, dtype=None, out=None)
|
| Return the cumulative sum of the elements along the given axis.
|
| Refer to `numpy.cumsum` for full documentation.
|
| See Also
| --------
| numpy.cumsum : equivalent function
|
| diagonal(...)
| a.diagonal(offset=0, axis1=0, axis2=1)
|
| Return specified diagonals. In NumPy 1.9 the returned array is a
| read-only view instead of a copy as in previous NumPy versions. In
| a future version the read-only restriction will be removed.
|
| Refer to :func:`numpy.diagonal` for full documentation.
|
| See Also
| --------
| numpy.diagonal : equivalent function
|
| dot(...)
|
| dump(...)
| a.dump(file)
|
| Dump a pickle of the array to the specified file.
| The array can be read back with pickle.load or numpy.load.
|
| Parameters
| ----------
| file : str or Path
| A string naming the dump file.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| dumps(...)
| a.dumps()
|
| Returns the pickle of the array as a string.
| pickle.loads will convert the string back to an array.
|
| Parameters
| ----------
| None
|
| fill(...)
| a.fill(value)
|
| Fill the array with a scalar value.
|
| Parameters
| ----------
| value : scalar
| All elements of `a` will be assigned this value.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([1, 2])
| >>> a.fill(0)
| >>> a
| array([0, 0])
| >>> a = np.empty(2)
| >>> a.fill(1)
| >>> a
| array([1., 1.])
|
| Fill expects a scalar value and always behaves the same as assigning
| to a single array element. The following is a rare example where this
| distinction is important:
|
| >>> a = np.array([None, None], dtype=object)
| >>> a[0] = np.array(3)
| >>> a
| array([array(3), None], dtype=object)
| >>> a.fill(np.array(3))
| >>> a
| array([array(3), array(3)], dtype=object)
|
| Where other forms of assignments will unpack the array being assigned:
|
| >>> a[...] = np.array(3)
| >>> a
| array([3, 3], dtype=object)
|
| flatten(...)
| a.flatten(order='C')
|
| Return a copy of the array collapsed into one dimension.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| 'C' means to flatten in row-major (C-style) order.
| 'F' means to flatten in column-major (Fortran-
| style) order. 'A' means to flatten in column-major
| order if `a` is Fortran *contiguous* in memory,
| row-major order otherwise. 'K' means to flatten
| `a` in the order the elements occur in memory.
| The default is 'C'.
|
| Returns
| -------
| y : ndarray
| A copy of the input array, flattened to one dimension.
|
| See Also
| --------
| ravel : Return a flattened array.
| flat : A 1-D flat iterator over the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,2], [3,4]])
| >>> a.flatten()
| array([1, 2, 3, 4])
| >>> a.flatten('F')
| array([1, 3, 2, 4])
|
| getfield(...)
| a.getfield(dtype, offset=0)
|
| Returns a field of the given array as a certain type.
|
| A field is a view of the array data with a given data-type. The values in
| the view are determined by the given type and the offset into the current
| array in bytes. The offset needs to be such that the view dtype fits in the
| array dtype; for example an array of dtype complex128 has 16-byte elements.
| If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| between 0 and 12 bytes.
|
| Parameters
| ----------
| dtype : str or dtype
| The data type of the view. The dtype size of the view can not be larger
| than that of the array itself.
| offset : int
| Number of bytes to skip before beginning the element view.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.diag([1.+1.j]*2)
| >>> x[1, 1] = 2 + 4.j
| >>> x
| array([[1.+1.j, 0.+0.j],
| [0.+0.j, 2.+4.j]])
| >>> x.getfield(np.float64)
| array([[1., 0.],
| [0., 2.]])
|
| By choosing an offset of 8 bytes we can select the complex part of the
| array for our view:
|
| >>> x.getfield(np.float64, offset=8)
| array([[1., 0.],
| [0., 4.]])
|
| item(...)
| a.item(*args)
|
| Copy an element of an array to a standard Python scalar and return it.
|
| Parameters
| ----------
| \*args : Arguments (variable number and type)
|
| * none: in this case, the method only works for arrays
| with one element (`a.size == 1`), which element is
| copied into a standard Python scalar object and returned.
|
| * int_type: this argument is interpreted as a flat index into
| the array, specifying which element to copy and return.
|
| * tuple of int_types: functions as does a single int_type argument,
| except that the argument is interpreted as an nd-index into the
| array.
|
| Returns
| -------
| z : Standard Python scalar object
| A copy of the specified element of the array as a suitable
| Python scalar
|
| Notes
| -----
| When the data type of `a` is longdouble or clongdouble, item() returns
| a scalar array object because there is no available Python scalar that
| would not lose information. Void arrays return a buffer object for item(),
| unless fields are defined, in which case a tuple is returned.
|
| `item` is very similar to a[args], except, instead of an array scalar,
| a standard Python scalar is returned. This can be useful for speeding up
| access to elements of the array and doing arithmetic on elements of the
| array using Python's optimized math.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.random.seed(123)
| >>> x = np.random.randint(9, size=(3, 3))
| >>> x
| array([[2, 2, 6],
| [1, 3, 6],
| [1, 0, 1]])
| >>> x.item(3)
| 1
| >>> x.item(7)
| 0
| >>> x.item((0, 1))
| 2
| >>> x.item((2, 2))
| 1
|
| For an array with object dtype, elements are returned as-is.
|
| >>> a = np.array([np.int64(1)], dtype=object)
| >>> a.item() #return np.int64
| np.int64(1)
|
| max(...)
| a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the maximum along a given axis.
|
| Refer to `numpy.amax` for full documentation.
|
| See Also
| --------
| numpy.amax : equivalent function
|
| mean(...)
| a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
|
| Returns the average of the array elements along given axis.
|
| Refer to `numpy.mean` for full documentation.
|
| See Also
| --------
| numpy.mean : equivalent function
|
| min(...)
| a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the minimum along a given axis.
|
| Refer to `numpy.amin` for full documentation.
|
| See Also
| --------
| numpy.amin : equivalent function
|
| nonzero(...)
| a.nonzero()
|
| Return the indices of the elements that are non-zero.
|
| Refer to `numpy.nonzero` for full documentation.
|
| See Also
| --------
| numpy.nonzero : equivalent function
|
| partition(...)
| a.partition(kth, axis=-1, kind='introselect', order=None)
|
| Partially sorts the elements in the array 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. In the output array, all elements smaller than the k-th element
| are located to the left of this element and all equal or greater are
| located to its right. The ordering of the elements in the two partitions
| on the either side of the k-th element in the output array is undefined.
|
| .. versionadded:: 1.8.0
|
| Parameters
| ----------
| kth : int or sequence of ints
| Element index to partition by. The kth element value 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 kth it will partition all elements
| indexed by kth of them into their sorted position at once.
|
| .. deprecated:: 1.22.0
| Passing booleans as index is deprecated.
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'introselect'}, optional
| Selection algorithm. Default is 'introselect'.
| order : str 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, and not all fields need to be specified,
| but unspecified fields will still be used, in the order in which
| they come up in the dtype, to break ties.
|
| See Also
| --------
| numpy.partition : Return a partitioned copy of an array.
| argpartition : Indirect partition.
| sort : Full sort.
|
| Notes
| -----
| See ``np.partition`` for notes on the different algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([3, 4, 2, 1])
| >>> a.partition(3)
| >>> a
| array([2, 1, 3, 4]) # may vary
|
| >>> a.partition((1, 3))
| >>> a
| array([1, 2, 3, 4])
|
| prod(...)
| a.prod(axis=None, dtype=None, out=None, keepdims=False,
| initial=1, where=True)
|
| Return the product of the array elements over the given axis
|
| Refer to `numpy.prod` for full documentation.
|
| See Also
| --------
| numpy.prod : equivalent function
|
| put(...)
| a.put(indices, values, mode='raise')
|
| Set ``a.flat[n] = values[n]`` for all `n` in indices.
|
| Refer to `numpy.put` for full documentation.
|
| See Also
| --------
| numpy.put : equivalent function
|
| ravel(...)
| a.ravel([order])
|
| Return a flattened array.
|
| Refer to `numpy.ravel` for full documentation.
|
| See Also
| --------
| numpy.ravel : equivalent function
|
| ndarray.flat : a flat iterator on the array.
|
| repeat(...)
| a.repeat(repeats, axis=None)
|
| Repeat elements of an array.
|
| Refer to `numpy.repeat` for full documentation.
|
| See Also
| --------
| numpy.repeat : equivalent function
|
| reshape(...)
| a.reshape(shape, /, *, order='C', copy=None)
|
| Returns an array containing the same data with a new shape.
|
| Refer to `numpy.reshape` for full documentation.
|
| See Also
| --------
| numpy.reshape : equivalent function
|
| Notes
| -----
| Unlike the free function `numpy.reshape`, this method on `ndarray` allows
| the elements of the shape parameter to be passed in as separate arguments.
| For example, ``a.reshape(10, 11)`` is equivalent to
| ``a.reshape((10, 11))``.
|
| resize(...)
| a.resize(new_shape, refcheck=True)
|
| Change shape and size of array in-place.
|
| Parameters
| ----------
| new_shape : tuple of ints, or `n` ints
| Shape of resized array.
| refcheck : bool, optional
| If False, reference count will not be checked. Default is True.
|
| Returns
| -------
| None
|
| Raises
| ------
| ValueError
| If `a` does not own its own data or references or views to it exist,
| and the data memory must be changed.
| PyPy only: will always raise if the data memory must be changed, since
| there is no reliable way to determine if references or views to it
| exist.
|
| SystemError
| If the `order` keyword argument is specified. This behaviour is a
| bug in NumPy.
|
| See Also
| --------
| resize : Return a new array with the specified shape.
|
| Notes
| -----
| This reallocates space for the data area if necessary.
|
| Only contiguous arrays (data elements consecutive in memory) can be
| resized.
|
| The purpose of the reference count check is to make sure you
| do not use this array as a buffer for another Python object and then
| reallocate the memory. However, reference counts can increase in
| other ways so if you are sure that you have not shared the memory
| for this array with another Python object, then you may safely set
| `refcheck` to False.
|
| Examples
| --------
| Shrinking an array: array is flattened (in the order that the data are
| stored in memory), resized, and reshaped:
|
| >>> import numpy as np
|
| >>> a = np.array([[0, 1], [2, 3]], order='C')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [1]])
|
| >>> a = np.array([[0, 1], [2, 3]], order='F')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [2]])
|
| Enlarging an array: as above, but missing entries are filled with zeros:
|
| >>> b = np.array([[0, 1], [2, 3]])
| >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
| >>> b
| array([[0, 1, 2],
| [3, 0, 0]])
|
| Referencing an array prevents resizing...
|
| >>> c = a
| >>> a.resize((1, 1))
| Traceback (most recent call last):
| ...
| ValueError: cannot resize an array that references or is referenced ...
|
| Unless `refcheck` is False:
|
| >>> a.resize((1, 1), refcheck=False)
| >>> a
| array([[0]])
| >>> c
| array([[0]])
|
| round(...)
| a.round(decimals=0, out=None)
|
| Return `a` with each element rounded to the given number of decimals.
|
| Refer to `numpy.around` for full documentation.
|
| See Also
| --------
| numpy.around : equivalent function
|
| searchsorted(...)
| a.searchsorted(v, side='left', sorter=None)
|
| Find indices where elements of v should be inserted in a to maintain order.
|
| For full documentation, see `numpy.searchsorted`
|
| See Also
| --------
| numpy.searchsorted : equivalent function
|
| setfield(...)
| a.setfield(val, dtype, offset=0)
|
| Put a value into a specified place in a field defined by a data-type.
|
| Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| bytes into the field.
|
| Parameters
| ----------
| val : object
| Value to be placed in field.
| dtype : dtype object
| Data-type of the field in which to place `val`.
| offset : int, optional
| The number of bytes into the field at which to place `val`.
|
| Returns
| -------
| None
|
| See Also
| --------
| getfield
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.eye(3)
| >>> x.getfield(np.float64)
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
| >>> x.setfield(3, np.int32)
| >>> x.getfield(np.int32)
| array([[3, 3, 3],
| [3, 3, 3],
| [3, 3, 3]], dtype=int32)
| >>> x
| array([[1.0e+000, 1.5e-323, 1.5e-323],
| [1.5e-323, 1.0e+000, 1.5e-323],
| [1.5e-323, 1.5e-323, 1.0e+000]])
| >>> x.setfield(np.eye(3), np.int32)
| >>> x
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
|
| setflags(...)
| a.setflags(write=None, align=None, uic=None)
|
| Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| respectively.
|
| These Boolean-valued flags affect how numpy interprets the memory
| area used by `a` (see Notes below). The ALIGNED flag can only
| be set to True if the data is actually aligned according to the type.
| The WRITEBACKIFCOPY flag can never be set
| to True. The flag WRITEABLE can only be set to True if the array owns its
| own memory, or the ultimate owner of the memory exposes a writeable buffer
| interface, or is a string. (The exception for string is made so that
| unpickling can be done without copying memory.)
|
| Parameters
| ----------
| write : bool, optional
| Describes whether or not `a` can be written to.
| align : bool, optional
| Describes whether or not `a` is aligned properly for its type.
| uic : bool, optional
| Describes whether or not `a` is a copy of another "base" array.
|
| Notes
| -----
| Array flags provide information about how the memory area used
| for the array is to be interpreted. There are 7 Boolean flags
| in use, only three of which can be changed by the user:
| WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
|
| WRITEABLE (W) the data area can be written to;
|
| ALIGNED (A) the data and strides are aligned appropriately for the hardware
| (as determined by the compiler);
|
| WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| called, the base array will be updated with the contents of this array.
|
| All flags can be accessed using the single (upper case) letter as well
| as the full name.
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.array([[3, 1, 7],
| ... [2, 0, 0],
| ... [8, 5, 9]])
| >>> y
| array([[3, 1, 7],
| [2, 0, 0],
| [8, 5, 9]])
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
| >>> y.setflags(write=0, align=0)
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : False
| ALIGNED : False
| WRITEBACKIFCOPY : False
| >>> y.setflags(uic=1)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: cannot set WRITEBACKIFCOPY flag to True
|
| sort(...)
| a.sort(axis=-1, kind=None, order=None)
|
| Sort an array in-place. Refer to `numpy.sort` for full documentation.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
| and 'mergesort' use timsort under the covers and, in general, the
| actual implementation will vary with datatype. The 'mergesort' option
| is retained for backwards compatibility.
|
| .. versionchanged:: 1.15.0
| The 'stable' option was added.
|
| order : str 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, and 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.
|
| See Also
| --------
| numpy.sort : Return a sorted copy of an array.
| numpy.argsort : Indirect sort.
| numpy.lexsort : Indirect stable sort on multiple keys.
| numpy.searchsorted : Find elements in sorted array.
| numpy.partition: Partial sort.
|
| Notes
| -----
| See `numpy.sort` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,4], [3,1]])
| >>> a.sort(axis=1)
| >>> a
| array([[1, 4],
| [1, 3]])
| >>> a.sort(axis=0)
| >>> a
| array([[1, 3],
| [1, 4]])
|
| Use the `order` keyword to specify a field to use when sorting a
| structured array:
|
| >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
| >>> a.sort(order='y')
| >>> a
| array([(b'c', 1), (b'a', 2)],
| dtype=[('x', 'S1'), ('y', '<i8')])
|
| squeeze(...)
| a.squeeze(axis=None)
|
| Remove axes of length one from `a`.
|
| Refer to `numpy.squeeze` for full documentation.
|
| See Also
| --------
| numpy.squeeze : equivalent function
|
| std(...)
| a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the standard deviation of the array elements along given axis.
|
| Refer to `numpy.std` for full documentation.
|
| See Also
| --------
| numpy.std : equivalent function
|
| sum(...)
| a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
|
| Return the sum of the array elements over the given axis.
|
| Refer to `numpy.sum` for full documentation.
|
| See Also
| --------
| numpy.sum : equivalent function
|
| swapaxes(...)
| a.swapaxes(axis1, axis2)
|
| Return a view of the array with `axis1` and `axis2` interchanged.
|
| Refer to `numpy.swapaxes` for full documentation.
|
| See Also
| --------
| numpy.swapaxes : equivalent function
|
| take(...)
| a.take(indices, axis=None, out=None, mode='raise')
|
| Return an array formed from the elements of `a` at the given indices.
|
| Refer to `numpy.take` for full documentation.
|
| See Also
| --------
| numpy.take : equivalent function
|
| to_device(...)
|
| tobytes(...)
| a.tobytes(order='C')
|
| Construct Python bytes containing the raw data bytes in the array.
|
| Constructs Python bytes showing a copy of the raw contents of
| data memory. The bytes object is produced in C-order by default.
| This behavior is controlled by the ``order`` parameter.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| order : {'C', 'F', 'A'}, optional
| Controls the memory layout of the bytes object. 'C' means C-order,
| 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
| Fortran contiguous, 'C' otherwise. Default is 'C'.
|
| Returns
| -------
| s : bytes
| Python bytes exhibiting a copy of `a`'s raw data.
|
| See also
| --------
| frombuffer
| Inverse of this operation, construct a 1-dimensional array from Python
| bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
| >>> x.tobytes()
| b'\x00\x00\x01\x00\x02\x00\x03\x00'
| >>> x.tobytes('C') == x.tobytes()
| True
| >>> x.tobytes('F')
| b'\x00\x00\x02\x00\x01\x00\x03\x00'
|
| tofile(...)
| a.tofile(fid, sep="", format="%s")
|
| Write array to a file as text or binary (default).
|
| Data is always written in 'C' order, independent of the order of `a`.
| The data produced by this method can be recovered using the function
| fromfile().
|
| Parameters
| ----------
| fid : file or str or Path
| An open file object, or a string containing a filename.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| sep : str
| Separator between array items for text output.
| If "" (empty), a binary file is written, equivalent to
| ``file.write(a.tobytes())``.
| format : str
| Format string for text file output.
| Each entry in the array is formatted to text by first converting
| it to the closest Python type, and then using "format" % item.
|
| Notes
| -----
| This is a convenience function for quick storage of array data.
| Information on endianness and precision is lost, so this method is not a
| good choice for files intended to archive data or transport data between
| machines with different endianness. Some of these problems can be overcome
| by outputting the data as text files, at the expense of speed and file
| size.
|
| When fid is a file object, array contents are directly written to the
| file, bypassing the file object's ``write`` method. As a result, tofile
| cannot be used with files objects supporting compression (e.g., GzipFile)
| or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
|
| tolist(...)
| a.tolist()
|
| Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
|
| Return a copy of the array data as a (nested) Python list.
| Data items are converted to the nearest compatible builtin Python type, via
| the `~numpy.ndarray.item` function.
|
| If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
| not be a list at all, but a simple Python scalar.
|
| Parameters
| ----------
| none
|
| Returns
| -------
| y : object, or list of object, or list of list of object, or ...
| The possibly nested list of array elements.
|
| Notes
| -----
| The array may be recreated via ``a = np.array(a.tolist())``, although this
| may sometimes lose precision.
|
| Examples
| --------
| For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
| except that ``tolist`` changes numpy scalars to Python scalars:
|
| >>> import numpy as np
| >>> a = np.uint32([1, 2])
| >>> a_list = list(a)
| >>> a_list
| [1, 2]
| >>> type(a_list[0])
| <class 'numpy.uint32'>
| >>> a_tolist = a.tolist()
| >>> a_tolist
| [1, 2]
| >>> type(a_tolist[0])
| <class 'int'>
|
| Additionally, for a 2D array, ``tolist`` applies recursively:
|
| >>> a = np.array([[1, 2], [3, 4]])
| >>> list(a)
| [array([1, 2]), array([3, 4])]
| >>> a.tolist()
| [[1, 2], [3, 4]]
|
| The base case for this recursion is a 0D array:
|
| >>> a = np.array(1)
| >>> list(a)
| Traceback (most recent call last):
| ...
| TypeError: iteration over a 0-d array
| >>> a.tolist()
| 1
|
| tostring(...)
| a.tostring(order='C')
|
| A compatibility alias for `~ndarray.tobytes`, with exactly the same
| behavior.
|
| Despite its name, it returns :class:`bytes` not :class:`str`\ s.
|
| .. deprecated:: 1.19.0
|
| trace(...)
| a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
|
| Return the sum along diagonals of the array.
|
| Refer to `numpy.trace` for full documentation.
|
| See Also
| --------
| numpy.trace : equivalent function
|
| transpose(...)
| a.transpose(*axes)
|
| Returns a view of the array with axes transposed.
|
| Refer to `numpy.transpose` for full documentation.
|
| Parameters
| ----------
| axes : None, tuple of ints, or `n` ints
|
| * None or no argument: reverses the order of the axes.
|
| * tuple of ints: `i` in the `j`-th place in the tuple means that the
| array's `i`-th axis becomes the transposed array's `j`-th axis.
|
| * `n` ints: same as an n-tuple of the same ints (this form is
| intended simply as a "convenience" alternative to the tuple form).
|
| Returns
| -------
| p : ndarray
| View of the array with its axes suitably permuted.
|
| See Also
| --------
| transpose : Equivalent function.
| ndarray.T : Array property returning the array transposed.
| ndarray.reshape : Give a new shape to an array without changing its data.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.transpose()
| array([[1, 3],
| [2, 4]])
| >>> a.transpose((1, 0))
| array([[1, 3],
| [2, 4]])
| >>> a.transpose(1, 0)
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.transpose()
| array([1, 2, 3, 4])
|
| var(...)
| a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the variance of the array elements, along given axis.
|
| Refer to `numpy.var` for full documentation.
|
| See Also
| --------
| numpy.var : equivalent function
|
| view(...)
| a.view([dtype][, type])
|
| New view of array with the same data.
|
| .. note::
| Passing None for ``dtype`` is different from omitting the parameter,
| since the former invokes ``dtype(None)`` which is an alias for
| ``dtype('float64')``.
|
| Parameters
| ----------
| dtype : data-type or ndarray sub-class, optional
| Data-type descriptor of the returned view, e.g., float32 or int16.
| Omitting it results in the view having the same data-type as `a`.
| This argument can also be specified as an ndarray sub-class, which
| then specifies the type of the returned object (this is equivalent to
| setting the ``type`` parameter).
| type : Python type, optional
| Type of the returned view, e.g., ndarray or matrix. Again, omission
| of the parameter results in type preservation.
|
| Notes
| -----
| ``a.view()`` is used two different ways:
|
| ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| of the array's memory with a different data-type. This can cause a
| reinterpretation of the bytes of memory.
|
| ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| returns an instance of `ndarray_subclass` that looks at the same array
| (same shape, dtype, etc.) This does not cause a reinterpretation of the
| memory.
|
| For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| bytes per entry than the previous dtype (for example, converting a regular
| array to a structured array), then the last axis of ``a`` must be
| contiguous. This axis will be resized in the result.
|
| .. versionchanged:: 1.23.0
| Only the last axis needs to be contiguous. Previously, the entire array
| had to be C-contiguous.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
|
| Viewing array data using a different type and dtype:
|
| >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
| >>> y = x.view(dtype=nonneg, type=np.recarray)
| >>> x["a"]
| array([-1], dtype=int8)
| >>> y.a
| array([255], dtype=uint8)
|
| Creating a view on a structured array so it can be used in calculations
|
| >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
| >>> xv = x.view(dtype=np.int8).reshape(-1,2)
| >>> xv
| array([[1, 2],
| [3, 4]], dtype=int8)
| >>> xv.mean(0)
| array([2., 3.])
|
| Making changes to the view changes the underlying array
|
| >>> xv[0,1] = 20
| >>> x
| array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
|
| Using a view to convert an array to a recarray:
|
| >>> z = x.view(np.recarray)
| >>> z.a
| array([1, 3], dtype=int8)
|
| Views share data:
|
| >>> x[0] = (9, 10)
| >>> z[0]
| np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
|
| Views that change the dtype size (bytes per entry) should normally be
| avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
|
| >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
| >>> y = x[:, ::2]
| >>> y
| array([[1, 3],
| [4, 6]], dtype=int16)
| >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
| Traceback (most recent call last):
| ...
| ValueError: To change to a dtype of a different size, the last axis must be contiguous
| >>> z = y.copy()
| >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
| array([[(1, 3)],
| [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
|
| However, views that change dtype are totally fine for arrays with a
| contiguous last axis, even if the rest of the axes are not C-contiguous:
|
| >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
| >>> x.transpose(1, 0, 2).view(np.int16)
| array([[[ 256, 770],
| [3340, 3854]],
| <BLANKLINE>
| [[1284, 1798],
| [4368, 4882]],
| <BLANKLINE>
| [[2312, 2826],
| [5396, 5910]]], dtype=int16)
|
| ----------------------------------------------------------------------
| Class methods inherited from ndarray:
|
| __class_getitem__(...)
| a.__class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.ndarray` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.ndarray` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.ndarray[Any, np.dtype[Any]]
| numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
| numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ndarray:
|
| T
| View of the transposed array.
|
| Same as ``self.transpose()``.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.T
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.T
| array([1, 2, 3, 4])
|
| See Also
| --------
| transpose
|
| __array_interface__
| Array protocol: Python side.
|
| __array_struct__
| Array protocol: C-struct side.
|
| base
| Base object if memory is from some other object.
|
| Examples
| --------
| The base of an array that owns its memory is None:
|
| >>> import numpy as np
| >>> x = np.array([1,2,3,4])
| >>> x.base is None
| True
|
| Slicing creates a view, whose memory is shared with x:
|
| >>> y = x[2:]
| >>> y.base is x
| True
|
| ctypes
| An object to simplify the interaction of the array with the ctypes
| module.
|
| This attribute creates an object that makes it easier to use arrays
| when calling shared libraries with the ctypes module. The returned
| object has, among others, data, shape, and strides attributes (see
| Notes below) which themselves return ctypes objects that can be used
| as arguments to a shared library.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| c : Python object
| Possessing attributes data, shape, strides, etc.
|
| See Also
| --------
| numpy.ctypeslib
|
| Notes
| -----
| Below are the public attributes of this object which were documented
| in "Guide to NumPy" (we have omitted undocumented public attributes,
| as well as documented private attributes):
|
| .. autoattribute:: numpy._core._internal._ctypes.data
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.shape
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.strides
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.data_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.shape_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.strides_as
| :noindex:
|
| If the ctypes module is not available, then the ctypes attribute
| of array objects still returns something useful, but ctypes objects
| are not returned and errors may be raised instead. In particular,
| the object will still have the ``as_parameter`` attribute which will
| return an integer equal to the data attribute.
|
| Examples
| --------
| >>> import numpy as np
| >>> import ctypes
| >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| >>> x
| array([[0, 1],
| [2, 3]], dtype=int32)
| >>> x.ctypes.data
| 31962608 # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| c_uint(0)
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| c_ulong(4294967296)
| >>> x.ctypes.shape
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| >>> x.ctypes.strides
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
|
| data
| Python buffer object pointing to the start of the array's data.
|
| device
|
| dtype
| Data-type of the array's elements.
|
| .. warning::
|
| Setting ``arr.dtype`` is discouraged and may be deprecated in the
| future. Setting will replace the ``dtype`` without modifying the
| memory (see also `ndarray.view` and `ndarray.astype`).
|
| Parameters
| ----------
| None
|
| Returns
| -------
| d : numpy dtype object
|
| See Also
| --------
| ndarray.astype : Cast the values contained in the array to a new data-type.
| ndarray.view : Create a view of the same data but a different data-type.
| numpy.dtype
|
| Examples
| --------
| >>> x
| array([[0, 1],
| [2, 3]])
| >>> x.dtype
| dtype('int32')
| >>> type(x.dtype)
| <type 'numpy.dtype'>
|
| flags
| Information about the memory layout of the array.
|
| Attributes
| ----------
| C_CONTIGUOUS (C)
| The data is in a single, C-style contiguous segment.
| F_CONTIGUOUS (F)
| The data is in a single, Fortran-style contiguous segment.
| OWNDATA (O)
| The array owns the memory it uses or borrows it from another object.
| WRITEABLE (W)
| The data area can be written to. Setting this to False locks
| the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| from its base array at creation time, but a view of a writeable
| array may be subsequently locked while the base array remains writeable.
| (The opposite is not true, in that a view of a locked array may not
| be made writeable. However, currently, locking a base object does not
| lock any views that already reference it, so under that circumstance it
| is possible to alter the contents of a locked array via a previously
| created writeable view onto it.) Attempting to change a non-writeable
| array raises a RuntimeError exception.
| ALIGNED (A)
| The data and all elements are aligned appropriately for the hardware.
| WRITEBACKIFCOPY (X)
| This array is a copy of some other array. The C-API function
| PyArray_ResolveWritebackIfCopy must be called before deallocating
| to the base array will be updated with the contents of this array.
| FNC
| F_CONTIGUOUS and not C_CONTIGUOUS.
| FORC
| F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| BEHAVED (B)
| ALIGNED and WRITEABLE.
| CARRAY (CA)
| BEHAVED and C_CONTIGUOUS.
| FARRAY (FA)
| BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
|
| Notes
| -----
| The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| names are only supported in dictionary access.
|
| Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| changed by the user, via direct assignment to the attribute or dictionary
| entry, or by calling `ndarray.setflags`.
|
| The array flags cannot be set arbitrarily:
|
| - WRITEBACKIFCOPY can only be set ``False``.
| - ALIGNED can only be set ``True`` if the data is truly aligned.
| - WRITEABLE can only be set ``True`` if the array owns its own memory
| or the ultimate owner of the memory exposes a writeable buffer
| interface or is a string.
|
| Arrays can be both C-style and Fortran-style contiguous simultaneously.
| This is clear for 1-dimensional arrays, but can also be true for higher
| dimensional arrays.
|
| Even for contiguous arrays a stride for a given dimension
| ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| or the array has no elements.
| It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| Fortran-style contiguous arrays is true.
|
| flat
| A 1-D iterator over the array.
|
| This is a `numpy.flatiter` instance, which acts similarly to, but is not
| a subclass of, Python's built-in iterator object.
|
| See Also
| --------
| flatten : Return a copy of the array collapsed into one dimension.
|
| flatiter
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(1, 7).reshape(2, 3)
| >>> x
| array([[1, 2, 3],
| [4, 5, 6]])
| >>> x.flat[3]
| 4
| >>> x.T
| array([[1, 4],
| [2, 5],
| [3, 6]])
| >>> x.T.flat[3]
| 5
| >>> type(x.flat)
| <class 'numpy.flatiter'>
|
| An assignment example:
|
| >>> x.flat = 3; x
| array([[3, 3, 3],
| [3, 3, 3]])
| >>> x.flat[[1,4]] = 1; x
| array([[3, 1, 3],
| [3, 1, 3]])
|
| imag
| The imaginary part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.imag
| array([ 0. , 0.70710678])
| >>> x.imag.dtype
| dtype('float64')
|
| itemset
|
| itemsize
| Length of one array element in bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1,2,3], dtype=np.float64)
| >>> x.itemsize
| 8
| >>> x = np.array([1,2,3], dtype=np.complex128)
| >>> x.itemsize
| 16
|
| mT
| View of the matrix transposed array.
|
| The matrix transpose is the transpose of the last two dimensions, even
| if the array is of higher dimension.
|
| .. versionadded:: 2.0
|
| Raises
| ------
| ValueError
| If the array is of dimension less than 2.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.mT
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.arange(8).reshape((2, 2, 2))
| >>> a
| array([[[0, 1],
| [2, 3]],
| <BLANKLINE>
| [[4, 5],
| [6, 7]]])
| >>> a.mT
| array([[[0, 2],
| [1, 3]],
| <BLANKLINE>
| [[4, 6],
| [5, 7]]])
|
| nbytes
| Total bytes consumed by the elements of the array.
|
| Notes
| -----
| Does not include memory consumed by non-element attributes of the
| array object.
|
| See Also
| --------
| sys.getsizeof
| Memory consumed by the object itself without parents in case view.
| This does include memory consumed by non-element attributes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3,5,2), dtype=np.complex128)
| >>> x.nbytes
| 480
| >>> np.prod(x.shape) * x.itemsize
| 480
|
| ndim
| Number of array dimensions.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3])
| >>> x.ndim
| 1
| >>> y = np.zeros((2, 3, 4))
| >>> y.ndim
| 3
|
| newbyteorder
|
| ptp
|
| real
| The real part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.real
| array([ 1. , 0.70710678])
| >>> x.real.dtype
| dtype('float64')
|
| See Also
| --------
| numpy.real : equivalent function
|
| shape
| Tuple of array dimensions.
|
| The shape property is usually used to get the current shape of an array,
| but may also be used to reshape the array in-place by assigning a tuple of
| array dimensions to it. As with `numpy.reshape`, one of the new shape
| dimensions can be -1, in which case its value is inferred from the size of
| the array and the remaining dimensions. Reshaping an array in-place will
| fail if a copy is required.
|
| .. warning::
|
| Setting ``arr.shape`` is discouraged and may be deprecated in the
| future. Using `ndarray.reshape` is the preferred approach.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3, 4])
| >>> x.shape
| (4,)
| >>> y = np.zeros((2, 3, 4))
| >>> y.shape
| (2, 3, 4)
| >>> y.shape = (3, 8)
| >>> y
| array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| >>> y.shape = (3, 6)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: total size of new array must be unchanged
| >>> np.zeros((4,2))[::2].shape = (-1,)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| AttributeError: Incompatible shape for in-place modification. Use
| `.reshape()` to make a copy with the desired shape.
|
| See Also
| --------
| numpy.shape : Equivalent getter function.
| numpy.reshape : Function similar to setting ``shape``.
| ndarray.reshape : Method similar to setting ``shape``.
|
| size
| Number of elements in the array.
|
| Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| dimensions.
|
| Notes
| -----
| `a.size` returns a standard arbitrary precision Python integer. This
| may not be the case with other methods of obtaining the same value
| (like the suggested ``np.prod(a.shape)``, which returns an instance
| of ``np.int_``), and may be relevant if the value is used further in
| calculations that may overflow a fixed size integer type.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| >>> x.size
| 30
| >>> np.prod(x.shape)
| 30
|
| strides
| Tuple of bytes to step in each dimension when traversing an array.
|
| The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| is::
|
| offset = sum(np.array(i) * a.strides)
|
| A more detailed explanation of strides can be found in
| :ref:`arrays.ndarray`.
|
| .. warning::
|
| Setting ``arr.strides`` is discouraged and may be deprecated in the
| future. `numpy.lib.stride_tricks.as_strided` should be preferred
| to create a new view of the same data in a safer way.
|
| Notes
| -----
| Imagine an array of 32-bit integers (each 4 bytes)::
|
| x = np.array([[0, 1, 2, 3, 4],
| [5, 6, 7, 8, 9]], dtype=np.int32)
|
| This array is stored in memory as 40 bytes, one after the other
| (known as a contiguous block of memory). The strides of an array tell
| us how many bytes we have to skip in memory to move to the next position
| along a certain axis. For example, we have to skip 4 bytes (1 value) to
| move to the next column, but 20 bytes (5 values) to get to the same
| position in the next row. As such, the strides for the array `x` will be
| ``(20, 4)``.
|
| See Also
| --------
| numpy.lib.stride_tricks.as_strided
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| >>> y
| array([[[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]],
| [[12, 13, 14, 15],
| [16, 17, 18, 19],
| [20, 21, 22, 23]]])
| >>> y.strides
| (48, 16, 4)
| >>> y[1,1,1]
| 17
| >>> offset=sum(y.strides * np.array((1,1,1)))
| >>> offset/y.itemsize
| 17
|
| >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| >>> x.strides
| (32, 4, 224, 1344)
| >>> i = np.array([3,5,2,2])
| >>> offset = sum(i * x.strides)
| >>> x[3,5,2,2]
| 813
| >>> offset / x.itemsize
| 813
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from ndarray:
|
| __hash__ = None
numpy.meshgrid
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
meshgrid(*xi, copy=True, sparse=False, indexing='xy')
Return a tuple of coordinate matrices from coordinate vectors.
Make N-D coordinate arrays for vectorized evaluations of
N-D scalar/vector fields over N-D grids, given
one-dimensional coordinate arrays x1, x2,..., xn.
.. versionchanged:: 1.9
1-D and 0-D cases are allowed.
Parameters
----------
x1, x2,..., xn : array_like
1-D arrays representing the coordinates of a grid.
indexing : {'xy', 'ij'}, optional
Cartesian ('xy', default) or matrix ('ij') indexing of output.
See Notes for more details.
.. versionadded:: 1.7.0
sparse : bool, optional
If True the shape of the returned coordinate array for dimension *i*
is reduced from ``(N1, ..., Ni, ... Nn)`` to
``(1, ..., 1, Ni, 1, ..., 1)``. These sparse coordinate grids are
intended to be use with :ref:`basics.broadcasting`. When all
coordinates are used in an expression, broadcasting still leads to a
fully-dimensonal result array.
Default is False.
.. versionadded:: 1.7.0
copy : bool, optional
If False, a view into the original arrays are returned in order to
conserve memory. Default is True. Please note that
``sparse=False, copy=False`` will likely return non-contiguous
arrays. Furthermore, more than one element of a broadcast array
may refer to a single memory location. If you need to write to the
arrays, make copies first.
.. versionadded:: 1.7.0
Returns
-------
X1, X2,..., XN : tuple of ndarrays
For vectors `x1`, `x2`,..., `xn` with lengths ``Ni=len(xi)``,
returns ``(N1, N2, N3,..., Nn)`` shaped arrays if indexing='ij'
or ``(N2, N1, N3,..., Nn)`` shaped arrays if indexing='xy'
with the elements of `xi` repeated to fill the matrix along
the first dimension for `x1`, the second for `x2` and so on.
Notes
-----
This function supports both indexing conventions through the indexing
keyword argument. Giving the string 'ij' returns a meshgrid with
matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing.
In the 2-D case with inputs of length M and N, the outputs are of shape
(N, M) for 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D case
with inputs of length M, N and P, outputs are of shape (N, M, P) for
'xy' indexing and (M, N, P) for 'ij' indexing. The difference is
illustrated by the following code snippet::
xv, yv = np.meshgrid(x, y, indexing='ij')
for i in range(nx):
for j in range(ny):
# treat xv[i,j], yv[i,j]
xv, yv = np.meshgrid(x, y, indexing='xy')
for i in range(nx):
for j in range(ny):
# treat xv[j,i], yv[j,i]
In the 1-D and 0-D case, the indexing and sparse keywords have no effect.
See Also
--------
mgrid : Construct a multi-dimensional "meshgrid" using indexing notation.
ogrid : Construct an open multi-dimensional "meshgrid" using indexing
notation.
:ref:`how-to-index`
Examples
--------
>>> import numpy as np
>>> nx, ny = (3, 2)
>>> x = np.linspace(0, 1, nx)
>>> y = np.linspace(0, 1, ny)
>>> xv, yv = np.meshgrid(x, y)
>>> xv
array([[0. , 0.5, 1. ],
[0. , 0.5, 1. ]])
>>> yv
array([[0., 0., 0.],
[1., 1., 1.]])
The result of `meshgrid` is a coordinate grid:
>>> import matplotlib.pyplot as plt
>>> plt.plot(xv, yv, marker='o', color='k', linestyle='none')
>>> plt.show()
You can create sparse output arrays to save memory and computation time.
>>> xv, yv = np.meshgrid(x, y, sparse=True)
>>> xv
array([[0. , 0.5, 1. ]])
>>> yv
array([[0.],
[1.]])
`meshgrid` is very useful to evaluate functions on a grid. If the
function depends on all coordinates, both dense and sparse outputs can be
used.
>>> x = np.linspace(-5, 5, 101)
>>> y = np.linspace(-5, 5, 101)
>>> # full coordinate arrays
>>> xx, yy = np.meshgrid(x, y)
>>> zz = np.sqrt(xx**2 + yy**2)
>>> xx.shape, yy.shape, zz.shape
((101, 101), (101, 101), (101, 101))
>>> # sparse coordinate arrays
>>> xs, ys = np.meshgrid(x, y, sparse=True)
>>> zs = np.sqrt(xs**2 + ys**2)
>>> xs.shape, ys.shape, zs.shape
((1, 101), (101, 1), (101, 101))
>>> np.array_equal(zz, zs)
True
>>> h = plt.contourf(x, y, zs)
>>> plt.axis('scaled')
>>> plt.colorbar()
>>> plt.show()
numpy.mgrid
Python Library Documentation: MGridClass in module numpy.lib._index_tricks_impl object class MGridClass(nd_grid) | An instance which returns a dense multi-dimensional "meshgrid". | | An instance which returns a dense (or fleshed out) mesh-grid | when indexed, so that each returned argument has the same shape. | The dimensions 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 : ndarray | A single array, containing a set of `ndarray`\ s all of the same | dimensions. stacked along the first axis. | | See Also | -------- | ogrid : like `mgrid` but returns open (not fleshed out) mesh grids | meshgrid: return coordinate matrices from coordinate vectors | r_ : array concatenator | :ref:`how-to-partition` | | Examples | -------- | >>> import numpy as np | >>> np.mgrid[0:5, 0:5] | array([[[0, 0, 0, 0, 0], | [1, 1, 1, 1, 1], | [2, 2, 2, 2, 2], | [3, 3, 3, 3, 3], | [4, 4, 4, 4, 4]], | [[0, 1, 2, 3, 4], | [0, 1, 2, 3, 4], | [0, 1, 2, 3, 4], | [0, 1, 2, 3, 4], | [0, 1, 2, 3, 4]]]) | >>> np.mgrid[-1:1:5j] | array([-1. , -0.5, 0. , 0.5, 1. ]) | | >>> np.mgrid[0:4].shape | (4,) | >>> np.mgrid[0:4, 0:5].shape | (2, 4, 5) | >>> np.mgrid[0:4, 0:5, 0:6].shape | (3, 4, 5, 6) | | Method resolution order: | MGridClass | nd_grid | builtins.object | | Methods defined here: | | __init__(self) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from nd_grid: | | __getitem__(self, key) | | ---------------------------------------------------------------------- | Data descriptors inherited from nd_grid: | | sparse
numpy.min
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
min(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the minimum of an array or minimum along an axis.
Parameters
----------
a : array_like
Input data.
axis : None or int or tuple of ints, optional
Axis or axes along which to operate. By default, flattened input is
used.
.. versionadded:: 1.7.0
If this is a tuple of ints, the minimum is selected over multiple axes,
instead of a single axis or all the axes as before.
out : ndarray, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
See :ref:`ufuncs-output-type` for more details.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the ``min`` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
initial : scalar, optional
The maximum value of an output element. Must be present to allow
computation on empty slice. See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.15.0
where : array_like of bool, optional
Elements to compare for the minimum. See `~numpy.ufunc.reduce`
for details.
.. versionadded:: 1.17.0
Returns
-------
min : ndarray or scalar
Minimum of `a`. If `axis` is None, the result is a scalar value.
If `axis` is an int, the result is an array of dimension
``a.ndim - 1``. If `axis` is a tuple, the result is an array of
dimension ``a.ndim - len(axis)``.
See Also
--------
amax :
The maximum value of an array along a given axis, propagating any NaNs.
nanmin :
The minimum value of an array along a given axis, ignoring any NaNs.
minimum :
Element-wise minimum of two arrays, propagating any NaNs.
fmin :
Element-wise minimum of two arrays, ignoring any NaNs.
argmin :
Return the indices of the minimum values.
nanmax, maximum, fmax
Notes
-----
NaN values are propagated, that is if at least one item is NaN, the
corresponding min value will be NaN as well. To ignore NaN values
(MATLAB behavior), please use nanmin.
Don't use `~numpy.min` for element-wise comparison of 2 arrays; when
``a.shape[0]`` is 2, ``minimum(a[0], a[1])`` is faster than
``min(a, axis=0)``.
Examples
--------
>>> import numpy as np
>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
[2, 3]])
>>> np.min(a) # Minimum of the flattened array
0
>>> np.min(a, axis=0) # Minima along the first axis
array([0, 1])
>>> np.min(a, axis=1) # Minima along the second axis
array([0, 2])
>>> np.min(a, where=[False, True], initial=10, axis=0)
array([10, 1])
>>> b = np.arange(5, dtype=float)
>>> b[2] = np.nan
>>> np.min(b)
np.float64(nan)
>>> np.min(b, where=~np.isnan(b), initial=10)
0.0
>>> np.nanmin(b)
0.0
>>> np.min([[-50], [10]], axis=-1, initial=0)
array([-50, 0])
Notice that the initial value is used as one of the elements for which the
minimum is determined, unlike for the default argument Python's max
function, which is only used for empty iterables.
Notice that this isn't the same as Python's ``default`` argument.
>>> np.min([6], initial=5)
5
>>> min([6], default=5)
6
numpy.min_scalar_type
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
min_scalar_type(...)
min_scalar_type(a, /)
For scalar ``a``, returns the data type with the smallest size
and smallest scalar kind which can hold its value. For non-scalar
array ``a``, returns the vector's dtype unmodified.
Floating point values are not demoted to integers,
and complex values are not demoted to floats.
Parameters
----------
a : scalar or array_like
The value whose minimal data type is to be found.
Returns
-------
out : dtype
The minimal data type.
Notes
-----
.. versionadded:: 1.6.0
See Also
--------
result_type, promote_types, dtype, can_cast
Examples
--------
>>> import numpy as np
>>> np.min_scalar_type(10)
dtype('uint8')
>>> np.min_scalar_type(-260)
dtype('int16')
>>> np.min_scalar_type(3.1)
dtype('float16')
>>> np.min_scalar_type(1e50)
dtype('float64')
>>> np.min_scalar_type(np.arange(4,dtype='f8'))
dtype('float64')
numpy.minimum
Python Library Documentation: ufunc
minimum = <ufunc 'minimum'>
minimum(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Element-wise minimum of array elements.
Compare two arrays and return a new array containing the element-wise
minima. If one of the elements being compared is a NaN, then that
element is returned. If both elements are NaNs then the first is
returned. The latter distinction is important for complex NaNs, which
are defined as at least one of the real or imaginary parts being a NaN.
The net effect is that NaNs are propagated.
Parameters
----------
x1, x2 : array_like
The arrays holding the elements to be compared.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The minimum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
maximum :
Element-wise maximum of two arrays, propagates NaNs.
fmin :
Element-wise minimum of two arrays, ignores NaNs.
amin :
The minimum value of an array along a given axis, propagates NaNs.
nanmin :
The minimum value of an array along a given axis, ignores NaNs.
fmax, amax, nanmax
Notes
-----
The minimum is equivalent to ``np.where(x1 <= x2, x1, x2)`` when
neither x1 nor x2 are NaNs, but it is faster and does proper
broadcasting.
Examples
--------
>>> import numpy as np
>>> np.minimum([2, 3, 4], [1, 5, 2])
array([1, 3, 2])
>>> np.minimum(np.eye(2), [0.5, 2]) # broadcasting
array([[ 0.5, 0. ],
[ 0. , 1. ]])
>>> np.minimum([np.nan, 0, np.nan],[0, np.nan, np.nan])
array([nan, nan, nan])
>>> np.minimum(-np.inf, 1)
-inf
numpy.mintypecode
Python Library Documentation: function mintypecode in module numpy
mintypecode(typechars, typeset='GDFgdf', default='d')
Return the character for the minimum-size type to which given types can
be safely cast.
The returned type character must represent the smallest size dtype such
that an array of the returned type can handle the data from an array of
all types in `typechars` (or if `typechars` is an array, then its
dtype.char).
Parameters
----------
typechars : list of str or array_like
If a list of strings, each string should represent a dtype.
If array_like, the character representation of the array dtype is used.
typeset : str or list of str, optional
The set of characters that the returned character is chosen from.
The default set is 'GDFgdf'.
default : str, optional
The default character, this is returned if none of the characters in
`typechars` matches a character in `typeset`.
Returns
-------
typechar : str
The character representing the minimum-size type that was found.
See Also
--------
dtype
Examples
--------
>>> import numpy as np
>>> np.mintypecode(['d', 'f', 'S'])
'd'
>>> x = np.array([1.1, 2-3.j])
>>> np.mintypecode(x)
'D'
>>> np.mintypecode('abceh', default='G')
'G'
numpy.mod
Python Library Documentation: ufunc
remainder = <ufunc 'remainder'>
remainder(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns the element-wise remainder of division.
Computes the remainder complementary to the `floor_divide` function. It is
equivalent to the Python modulus operator ``x1 % x2`` and has the same sign
as the divisor `x2`. The MATLAB function equivalent to ``np.remainder``
is ``mod``.
.. warning::
This should not be confused with:
* Python 3.7's `math.remainder` and C's ``remainder``, which
computes the IEEE remainder, which are the complement to
``round(x1 / x2)``.
* The MATLAB ``rem`` function and or the C ``%`` operator which is the
complement to ``int(x1 / x2)``.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The element-wise remainder of the quotient ``floor_divide(x1, x2)``.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
floor_divide : Equivalent of Python ``//`` operator.
divmod : Simultaneous floor division and remainder.
fmod : Equivalent of the MATLAB ``rem`` function.
divide, floor
Notes
-----
Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of)
integers.
``mod`` is an alias of ``remainder``.
Examples
--------
>>> import numpy as np
>>> np.remainder([4, 7], [2, 3])
array([0, 1])
>>> np.remainder(np.arange(7), 5)
array([0, 1, 2, 3, 4, 0, 1])
The ``%`` operator can be used as a shorthand for ``np.remainder`` on
ndarrays.
>>> x1 = np.arange(7)
>>> x1 % 5
array([0, 1, 2, 3, 4, 0, 1])
numpy.modf
Python Library Documentation: ufunc
modf = <ufunc 'modf'>
modf(x[, out1, out2], / [, out=(None, None)], *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the fractional and integral parts of an array, element-wise.
The fractional and integral parts are negative if the given number is
negative.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y1 : ndarray
Fractional part of `x`.
This is a scalar if `x` is a scalar.
y2 : ndarray
Integral part of `x`.
This is a scalar if `x` is a scalar.
Notes
-----
For integer input the return values are floats.
See Also
--------
divmod : ``divmod(x, 1)`` is equivalent to ``modf`` with the return values
switched, except it always has a positive remainder.
Examples
--------
>>> import numpy as np
>>> np.modf([0, 3.5])
(array([ 0. , 0.5]), array([ 0., 3.]))
>>> np.modf(-0.5)
(-0.5, -0)
numpy.moveaxis
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
moveaxis(a, source, destination)
Move axes of an array to new positions.
Other axes remain in their original order.
.. versionadded:: 1.11.0
Parameters
----------
a : np.ndarray
The array whose axes should be reordered.
source : int or sequence of int
Original positions of the axes to move. These must be unique.
destination : int or sequence of int
Destination positions for each of the original axes. These must also be
unique.
Returns
-------
result : np.ndarray
Array with moved axes. This array is a view of the input array.
See Also
--------
transpose : Permute the dimensions of an array.
swapaxes : Interchange two axes of an array.
Examples
--------
>>> import numpy as np
>>> x = np.zeros((3, 4, 5))
>>> np.moveaxis(x, 0, -1).shape
(4, 5, 3)
>>> np.moveaxis(x, -1, 0).shape
(5, 3, 4)
These all achieve the same result:
>>> np.transpose(x).shape
(5, 4, 3)
>>> np.swapaxes(x, 0, -1).shape
(5, 4, 3)
>>> np.moveaxis(x, [0, 1], [-1, -2]).shape
(5, 4, 3)
>>> np.moveaxis(x, [0, 1, 2], [-1, -2, -3]).shape
(5, 4, 3)
numpy.multiply
Python Library Documentation: ufunc
multiply = <ufunc 'multiply'>
multiply(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Multiply arguments element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays to be multiplied.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The product of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` * `x2` in terms of array broadcasting.
Examples
--------
>>> import numpy as np
>>> np.multiply(2.0, 4.0)
8.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.multiply(x1, x2)
array([[ 0., 1., 4.],
[ 0., 4., 10.],
[ 0., 7., 16.]])
The ``*`` operator can be used as a shorthand for ``np.multiply`` on
ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 * x2
array([[ 0., 1., 4.],
[ 0., 4., 10.],
[ 0., 7., 16.]])
numpy.nan
Python Library Documentation: float object
class float(object)
| float(x=0, /)
|
| Convert a string or number to a floating-point number, if possible.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(self, /)
| Return the ceiling as an Integral.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(self, /)
| Return the floor as an Integral.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Formats the float according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __round__(self, ndigits=None, /)
| Return the Integral closest to x, rounding half toward even.
|
| When an argument is passed, work like built-in round(x, ndigits).
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| as_integer_ratio(self, /)
| Return a pair of integers, whose ratio is exactly equal to the original float.
|
| The ratio is in lowest terms and has a positive denominator. Raise
| OverflowError on infinities and a ValueError on NaNs.
|
| >>> (10.0).as_integer_ratio()
| (10, 1)
| >>> (0.0).as_integer_ratio()
| (0, 1)
| >>> (-.25).as_integer_ratio()
| (-1, 4)
|
| conjugate(self, /)
| Return self, the complex conjugate of any float.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> 3.14159.hex()
| '0x1.921f9f01b866ep+1'
|
| is_integer(self, /)
| Return True if the float is an integer.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __getformat__(typestr, /)
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
| little-endian' best describes the format of floating-point numbers used by the
| C type named by typestr.
|
| fromhex(string, /)
| Create a floating-point number from a hexadecimal string.
|
| >>> float.fromhex('0x1.ffffp10')
| 2047.984375
| >>> float.fromhex('-0x1p-1074')
| -5e-324
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| imag
| the imaginary part of a complex number
|
| real
| the real part of a complex number
numpy.nan_to_num
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None)
Replace NaN with zero and infinity with large finite numbers (default
behaviour) or with the numbers defined by the user using the `nan`,
`posinf` and/or `neginf` keywords.
If `x` is inexact, NaN is replaced by zero or by the user defined value in
`nan` keyword, infinity is replaced by the largest finite floating point
values representable by ``x.dtype`` or by the user defined value in
`posinf` keyword and -infinity is replaced by the most negative finite
floating point values representable by ``x.dtype`` or by the user defined
value in `neginf` keyword.
For complex dtypes, the above is applied to each of the real and
imaginary components of `x` separately.
If `x` is not inexact, then no replacements are made.
Parameters
----------
x : scalar or array_like
Input data.
copy : bool, optional
Whether to create a copy of `x` (True) or to replace values
in-place (False). The in-place operation only occurs if
casting to an array does not require a copy.
Default is True.
.. versionadded:: 1.13
nan : int, float, optional
Value to be used to fill NaN values. If no value is passed
then NaN values will be replaced with 0.0.
.. versionadded:: 1.17
posinf : int, float, optional
Value to be used to fill positive infinity values. If no value is
passed then positive infinity values will be replaced with a very
large number.
.. versionadded:: 1.17
neginf : int, float, optional
Value to be used to fill negative infinity values. If no value is
passed then negative infinity values will be replaced with a very
small (or negative) number.
.. versionadded:: 1.17
Returns
-------
out : ndarray
`x`, with the non-finite values replaced. If `copy` is False, this may
be `x` itself.
See Also
--------
isinf : Shows which elements are positive or negative infinity.
isneginf : Shows which elements are negative infinity.
isposinf : Shows which elements are positive infinity.
isnan : Shows which elements are Not a Number (NaN).
isfinite : Shows which elements are finite (not NaN, not 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.
Examples
--------
>>> import numpy as np
>>> np.nan_to_num(np.inf)
1.7976931348623157e+308
>>> np.nan_to_num(-np.inf)
-1.7976931348623157e+308
>>> np.nan_to_num(np.nan)
0.0
>>> x = np.array([np.inf, -np.inf, np.nan, -128, 128])
>>> np.nan_to_num(x)
array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary
-1.28000000e+002, 1.28000000e+002])
>>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333)
array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03,
-1.2800000e+02, 1.2800000e+02])
>>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)])
array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary
-1.28000000e+002, 1.28000000e+002])
>>> np.nan_to_num(y)
array([ 1.79769313e+308 +0.00000000e+000j, # may vary
0.00000000e+000 +0.00000000e+000j,
0.00000000e+000 +1.79769313e+308j])
>>> np.nan_to_num(y, nan=111111, posinf=222222)
array([222222.+111111.j, 111111. +0.j, 111111.+222222.j])
numpy.nanargmax
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanargmax(a, axis=None, out=None, *, keepdims=<no value>)
Return the indices of the maximum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the
results cannot be trusted if a slice contains only NaNs and -Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
out : array, optional
If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype.
.. versionadded:: 1.22.0
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.
.. versionadded:: 1.22.0
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmax, nanargmin
Examples
--------
>>> import numpy as np
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmax(a)
0
>>> np.nanargmax(a)
1
>>> np.nanargmax(a, axis=0)
array([1, 0])
>>> np.nanargmax(a, axis=1)
array([1, 1])
numpy.nanargmin
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanargmin(a, axis=None, out=None, *, keepdims=<no value>)
Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
out : array, optional
If provided, the result will be inserted into this array. It should
be of the appropriate shape and dtype.
.. versionadded:: 1.22.0
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the array.
.. versionadded:: 1.22.0
Returns
-------
index_array : ndarray
An array of indices or a single index value.
See Also
--------
argmin, nanargmax
Examples
--------
>>> import numpy as np
>>> a = np.array([[np.nan, 4], [2, 3]])
>>> np.argmin(a)
0
>>> np.nanargmin(a)
2
>>> np.nanargmin(a, axis=0)
array([1, 1])
>>> np.nanargmin(a, axis=1)
array([1, 0])
numpy.nancumprod
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nancumprod(a, axis=None, dtype=None, out=None)
Return the cumulative product of array elements over a given axis treating Not a
Numbers (NaNs) as one. The cumulative product does not change when NaNs are
encountered and leading NaNs are replaced by ones.
Ones are returned for slices that are all-NaN or empty.
.. versionadded:: 1.12.0
Parameters
----------
a : array_like
Input array.
axis : int, optional
Axis along which the cumulative product is computed. By default
the input is flattened.
dtype : dtype, optional
Type of the returned array, as well as of the accumulator in which
the elements are multiplied. If *dtype* is not specified, it
defaults to the dtype of `a`, unless `a` has an integer dtype with
a precision less than that of the default platform integer. In
that case, the default platform integer is used instead.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type of the resulting values will be cast if necessary.
Returns
-------
nancumprod : ndarray
A new array holding the result is returned unless `out` is
specified, in which case it is returned.
See Also
--------
numpy.cumprod : Cumulative product across array propagating NaNs.
isnan : Show which elements are NaN.
Examples
--------
>>> import numpy as np
>>> np.nancumprod(1)
array([1])
>>> np.nancumprod([1])
array([1])
>>> np.nancumprod([1, np.nan])
array([1., 1.])
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nancumprod(a)
array([1., 2., 6., 6.])
>>> np.nancumprod(a, axis=0)
array([[1., 2.],
[3., 2.]])
>>> np.nancumprod(a, axis=1)
array([[1., 2.],
[3., 3.]])
numpy.nancumsum
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nancumsum(a, axis=None, dtype=None, out=None)
Return the cumulative sum of array elements over a given axis treating Not a
Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are
encountered and leading NaNs are replaced by zeros.
Zeros are returned for slices that are all-NaN or empty.
.. versionadded:: 1.12.0
Parameters
----------
a : array_like
Input array.
axis : int, optional
Axis along which the cumulative sum is computed. The default
(None) is to compute the cumsum over the flattened array.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults
to the dtype of `a`, unless `a` has an integer dtype with a
precision less than that of the default platform integer. In
that case, the default platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary. See :ref:`ufuncs-output-type` for
more details.
Returns
-------
nancumsum : ndarray.
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.cumsum : Cumulative sum across array propagating NaNs.
isnan : Show which elements are NaN.
Examples
--------
>>> import numpy as np
>>> np.nancumsum(1)
array([1])
>>> np.nancumsum([1])
array([1])
>>> np.nancumsum([1, np.nan])
array([1., 1.])
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nancumsum(a)
array([1., 3., 6., 6.])
>>> np.nancumsum(a, axis=0)
array([[1., 2.],
[4., 2.]])
>>> np.nancumsum(a, axis=1)
array([[1., 3.],
[3., 3.]])
numpy.nanmax
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanmax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the maximum of an array or maximum along an axis, ignoring any
NaNs. When all-NaN slices are encountered a ``RuntimeWarning`` is
raised and NaN is returned for that slice.
Parameters
----------
a : array_like
Array containing numbers whose maximum 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 maximum is computed. The default is to compute
the maximum of the flattened array.
out : ndarray, 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
:ref:`ufuncs-output-type` for more details.
.. versionadded:: 1.8.0
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
If the value is anything but the default, then
`keepdims` will be passed through to the `max` method
of sub-classes of `ndarray`. If the sub-classes methods
does not implement `keepdims` any exceptions will be raised.
.. versionadded:: 1.8.0
initial : scalar, optional
The minimum value of an output element. Must be present to allow
computation on empty slice. See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.22.0
where : array_like of bool, optional
Elements to compare for the maximum. See `~numpy.ufunc.reduce`
for details.
.. versionadded:: 1.22.0
Returns
-------
nanmax : ndarray
An array with the same shape as `a`, with the specified axis removed.
If `a` is a 0-d array, or if axis is None, an ndarray scalar is
returned. The same dtype as `a` is returned.
See Also
--------
nanmin :
The minimum value of an array along a given axis, ignoring any NaNs.
amax :
The maximum value of an array along a given axis, propagating any NaNs.
fmax :
Element-wise maximum of two arrays, ignoring any NaNs.
maximum :
Element-wise maximum of two arrays, propagating any NaNs.
isnan :
Shows which elements are Not a Number (NaN).
isfinite:
Shows which elements are neither NaN nor infinity.
amin, fmin, minimum
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.
Positive infinity is treated as a very large number and negative
infinity is treated as a very small (i.e. negative) number.
If the input has a integer type the function is equivalent to np.max.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmax(a)
3.0
>>> np.nanmax(a, axis=0)
array([3., 2.])
>>> np.nanmax(a, axis=1)
array([2., 3.])
When positive infinity and negative infinity are present:
>>> np.nanmax([1, 2, np.nan, -np.inf])
2.0
>>> np.nanmax([1, 2, np.nan, np.inf])
inf
numpy.nanmean
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanmean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>)
Compute the arithmetic mean along the specified axis, ignoring NaNs.
Returns the average of the array elements. The average is taken over
the flattened array by default, otherwise over the specified axis.
`float64` intermediate and return values are used for integer inputs.
For all-NaN slices, NaN is returned and a `RuntimeWarning` is raised.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Array containing numbers whose mean 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 means are computed. The default is to compute
the mean of the flattened array.
dtype : data-type, optional
Type to use in computing the mean. For integer inputs, the default
is `float64`; for inexact inputs, it is the same as the input
dtype.
out : ndarray, 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 :ref:`ufuncs-output-type` for more details.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `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.
where : array_like of bool, optional
Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.22.0
Returns
-------
m : ndarray, see dtype parameter above
If `out=None`, returns a new array containing the mean values,
otherwise a reference to the output array is returned. Nan is
returned for slices that contain only NaNs.
See Also
--------
average : Weighted average
mean : Arithmetic mean taken while not ignoring NaNs
var, nanvar
Notes
-----
The arithmetic mean is the sum of the non-NaN elements along the axis
divided by the number of non-NaN elements.
Note that for floating-point input, the mean 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`. Specifying a
higher-precision accumulator using the `dtype` keyword can alleviate
this issue.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.nanmean(a)
2.6666666666666665
>>> np.nanmean(a, axis=0)
array([2., 4.])
>>> np.nanmean(a, axis=1)
array([1., 3.5]) # may vary
numpy.nanmedian
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=<no value>)
Compute the median along the specified axis, while ignoring NaNs.
Returns the median of the array elements.
.. versionadded:: 1.9.0
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : {int, sequence of int, None}, optional
Axis or axes along which the medians are computed. The default
is to compute the median along a flattened version of the array.
A sequence of axes is supported since version 1.9.0.
out : ndarray, 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_input : bool, optional
If True, then allow use of memory of input array `a` for
calculations. The input array will be modified by the call to
`median`. This will save memory when you do not need to preserve
the contents of the input array. Treat the input as undefined,
but it will probably be fully or partially sorted. Default is
False. If `overwrite_input` is ``True`` and `a` is not already an
`ndarray`, an error will be raised.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `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.
Returns
-------
median : ndarray
A new array holding the result. If the input contains integers
or floats smaller than ``float64``, then the output data-type is
``np.float64``. Otherwise, the data-type of the output is the
same as that of the input. If `out` is specified, that array is
returned instead.
See Also
--------
mean, median, percentile
Notes
-----
Given a vector ``V`` of length ``N``, the median of ``V`` is the
middle value of a sorted copy of ``V``, ``V_sorted`` - i.e.,
``V_sorted[(N-1)/2]``, when ``N`` is odd and the average of the two
middle values of ``V_sorted`` when ``N`` is even.
Examples
--------
>>> import numpy as np
>>> a = np.array([[10.0, 7, 4], [3, 2, 1]])
>>> a[0, 1] = np.nan
>>> a
array([[10., nan, 4.],
[ 3., 2., 1.]])
>>> np.median(a)
np.float64(nan)
>>> np.nanmedian(a)
3.0
>>> np.nanmedian(a, axis=0)
array([6.5, 2. , 2.5])
>>> np.median(a, axis=1)
array([nan, 2.])
>>> b = a.copy()
>>> np.nanmedian(b, axis=1, overwrite_input=True)
array([7., 2.])
>>> assert not np.all(a==b)
>>> b = a.copy()
>>> np.nanmedian(b, axis=None, overwrite_input=True)
3.0
>>> assert not np.all(a==b)
numpy.nanmin
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanmin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return minimum of an array or minimum along an axis, ignoring any NaNs.
When all-NaN slices are encountered a ``RuntimeWarning`` is raised and
Nan is returned for that slice.
Parameters
----------
a : array_like
Array containing numbers whose minimum 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 minimum is computed. The default is to compute
the minimum of the flattened array.
out : ndarray, 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
:ref:`ufuncs-output-type` for more details.
.. versionadded:: 1.8.0
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
If the value is anything but the default, then
`keepdims` will be passed through to the `min` method
of sub-classes of `ndarray`. If the sub-classes methods
does not implement `keepdims` any exceptions will be raised.
.. versionadded:: 1.8.0
initial : scalar, optional
The maximum value of an output element. Must be present to allow
computation on empty slice. See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.22.0
where : array_like of bool, optional
Elements to compare for the minimum. See `~numpy.ufunc.reduce`
for details.
.. versionadded:: 1.22.0
Returns
-------
nanmin : ndarray
An array with the same shape as `a`, with the specified axis
removed. If `a` is a 0-d array, or if axis is None, an ndarray
scalar is returned. The same dtype as `a` is returned.
See Also
--------
nanmax :
The maximum value of an array along a given axis, ignoring any NaNs.
amin :
The minimum value of an array along a given axis, propagating any NaNs.
fmin :
Element-wise minimum of two arrays, ignoring any NaNs.
minimum :
Element-wise minimum of two arrays, propagating any NaNs.
isnan :
Shows which elements are Not a Number (NaN).
isfinite:
Shows which elements are neither NaN nor infinity.
amax, fmax, maximum
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.
Positive infinity is treated as a very large number and negative
infinity is treated as a very small (i.e. negative) number.
If the input has a integer type the function is equivalent to np.min.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmin(a)
1.0
>>> np.nanmin(a, axis=0)
array([1., 2.])
>>> np.nanmin(a, axis=1)
array([1., 3.])
When positive infinity and negative infinity are present:
>>> np.nanmin([1, 2, np.nan, np.inf])
1.0
>>> np.nanmin([1, 2, np.nan, -np.inf])
-inf
numpy.nanpercentile
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanpercentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=<no value>, *, weights=None, interpolation=None)
Compute the qth percentile of the data along the specified axis,
while ignoring nan values.
Returns the qth percentile(s) of the array elements.
.. versionadded:: 1.9.0
Parameters
----------
a : array_like
Input array or object that can be converted to an array, containing
nan values to be ignored.
q : array_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.
out : ndarray, 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_input : bool, 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.
method : str, 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:
1. 'inverted_cdf'
2. 'averaged_inverted_cdf'
3. 'closest_observation'
4. 'interpolated_inverted_cdf'
5. 'hazen'
6. 'weibull'
7. 'linear' (default)
8. 'median_unbiased'
9. 'normal_unbiased'
The first three methods are discontinuous. NumPy further defines the
following discontinuous variations of the default 'linear' (7.) option:
* 'lower'
* 'higher',
* 'midpoint'
* 'nearest'
.. versionchanged:: 1.22.0
This argument was previously called "interpolation" and only
offered the "linear" default and last four options.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left in
the result as dimensions with size one. With this option, the
result will broadcast correctly against the original array `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.
weights : array_like, optional
An array of weights associated with the values in `a`. Each value in
`a` contributes to the percentile according to its associated weight.
The weights array can either be 1-D (in which case its length must be
the size of `a` along the given axis) or of the same shape as `a`.
If `weights=None`, then all data in `a` are assumed to have a
weight equal to one.
Only `method="inverted_cdf"` supports weights.
.. versionadded:: 2.0.0
interpolation : str, optional
Deprecated name for the method keyword argument.
.. deprecated:: 1.22.0
Returns
-------
percentile : scalar 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
-----
The behavior of `numpy.nanpercentile` with percentage `q` is that of
`numpy.quantile` with argument ``q/100`` (ignoring nan values).
For more information, please see `numpy.quantile`.
Examples
--------
>>> import numpy as np
>>> 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)
np.float64(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)
References
----------
.. [1] R. J. Hyndman and Y. Fan,
"Sample quantiles in statistical packages,"
The American Statistician, 50(4), pp. 361-365, 1996
numpy.nanprod
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanprod(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
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.
.. versionadded:: 1.10.0
Parameters
----------
a : array_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.
dtype : data-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.
out : ndarray, 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
:ref:`ufuncs-output-type` for more details. The casting of NaN to integer
can yield unexpected results.
keepdims : bool, 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`.
initial : scalar, optional
The starting value for this product. See `~numpy.ufunc.reduce`
for details.
.. versionadded:: 1.22.0
where : array_like of bool, optional
Elements to include in the product. See `~numpy.ufunc.reduce`
for details.
.. versionadded:: 1.22.0
Returns
-------
nanprod : ndarray
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
--------
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanquantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=<no value>, *, weights=None, interpolation=None)
Compute the qth quantile of the data along the specified axis,
while ignoring nan values.
Returns the qth quantile(s) of the array elements.
.. versionadded:: 1.15.0
Parameters
----------
a : array_like
Input array or object that can be converted to an array, containing
nan values to be ignored
q : array_like of float
Probability or sequence of probabilities for the quantiles to compute.
Values 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.
out : ndarray, 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_input : bool, 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.
method : str, 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:
1. 'inverted_cdf'
2. 'averaged_inverted_cdf'
3. 'closest_observation'
4. 'interpolated_inverted_cdf'
5. 'hazen'
6. 'weibull'
7. 'linear' (default)
8. 'median_unbiased'
9. 'normal_unbiased'
The first three methods are discontinuous. NumPy further defines the
following discontinuous variations of the default 'linear' (7.) option:
* 'lower'
* 'higher',
* 'midpoint'
* 'nearest'
.. versionchanged:: 1.22.0
This argument was previously called "interpolation" and only
offered the "linear" default and last four options.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left in
the result as dimensions with size one. With this option, the
result will broadcast correctly against the original array `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.
weights : array_like, optional
An array of weights associated with the values in `a`. Each value in
`a` contributes to the quantile according to its associated weight.
The weights array can either be 1-D (in which case its length must be
the size of `a` along the given axis) or of the same shape as `a`.
If `weights=None`, then all data in `a` are assumed to have a
weight equal to one.
Only `method="inverted_cdf"` supports weights.
.. versionadded:: 2.0.0
interpolation : str, optional
Deprecated name for the method keyword argument.
.. deprecated:: 1.22.0
Returns
-------
quantile : scalar or ndarray
If `q` is a single probability and `axis=None`, then the result
is a scalar. If multiple probability levels 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
-----
The behavior of `numpy.nanquantile` is the same as that of
`numpy.quantile` (ignoring nan values).
For more information, please see `numpy.quantile`.
Examples
--------
>>> import numpy as np
>>> 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)
np.float64(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)
References
----------
.. [1] R. J. Hyndman and Y. Fan,
"Sample quantiles in statistical packages,"
The American Statistician, 50(4), pp. 361-365, 1996
numpy.nanstd
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>, mean=<no value>, correction=<no value>)
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.
.. versionadded:: 1.8.0
Parameters
----------
a : array_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.
dtype : dtype, 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.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type (of the
calculated values) will be cast if necessary.
ddof : {int, float}, 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.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `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.
where : array_like of bool, optional
Elements to include in the standard deviation.
See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.22.0
mean : array_like, optional
Provide the mean to prevent its recalculation. The mean should have
a shape as if it was calculated with ``keepdims=True``.
The axis for the calculation of the mean should be the same as used in
the call to this std function.
.. versionadded:: 1.26.0
correction : {int, float}, optional
Array API compatible name for the ``ddof`` parameter. Only one of them
can be provided at the same time.
.. versionadded:: 2.0.0
Returns
-------
standard_deviation : ndarray, 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
:ref:`ufuncs-output-type`
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
--------
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nansum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
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
----------
a : array_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.
dtype : data-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.
.. versionadded:: 1.8.0
out : ndarray, 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
:ref:`ufuncs-output-type` for more details. The casting of NaN to integer
can yield unexpected results.
.. versionadded:: 1.8.0
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `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.
.. versionadded:: 1.8.0
initial : scalar, optional
Starting value for the sum. See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.22.0
where : array_like of bool, optional
Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.22.0
Returns
-------
nansum : ndarray.
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
--------
>>> import numpy as np
>>> 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.inf])
-inf
>>> from numpy.testing import suppress_warnings
>>> with np.errstate(invalid="ignore"):
... np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present
np.float64(nan)
numpy.nanvar
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>, mean=<no value>, correction=<no value>)
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.
.. versionadded:: 1.8.0
Parameters
----------
a : array_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.
dtype : data-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.
out : ndarray, 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.
ddof : {int, float}, 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.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `a`.
where : array_like of bool, optional
Elements to include in the variance. See `~numpy.ufunc.reduce` for
details.
.. versionadded:: 1.22.0
mean : array_like, optional
Provide the mean to prevent its recalculation. The mean should have
a shape as if it was calculated with ``keepdims=True``.
The axis for the calculation of the mean should be the same as used in
the call to this var function.
.. versionadded:: 1.26.0
correction : {int, float}, optional
Array API compatible name for the ``ddof`` parameter. Only one of them
can be provided at the same time.
.. versionadded:: 2.0.0
Returns
-------
variance : ndarray, 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
:ref:`ufuncs-output-type`
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
--------
>>> import numpy as np
>>> 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
Python Library Documentation: class ndarray in module numpy
class ndarray(builtins.object)
| ndarray(shape, dtype=float, buffer=None, offset=0,
| strides=None, order=None)
|
| 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)
|
| shape : tuple of ints
| Shape of created array.
| dtype : data-type, optional
| Any object that can be interpreted as a numpy data type.
| buffer : object exposing buffer interface, optional
| Used to fill the array with data.
| offset : int, optional
| Offset of array data in buffer.
| strides : tuple of ints, optional
| Strides of data in memory.
| order : {'C', 'F'}, optional
| Row-major (C-style) or column-major (Fortran-style) order.
|
| Attributes
| ----------
| T : ndarray
| Transpose of the array.
| data : buffer
| The array's elements, in memory.
| dtype : dtype object
| Describes the format of the elements in the array.
| flags : dict
| Dictionary containing information related to memory use, e.g.,
| 'C_CONTIGUOUS', 'OWNDATA', 'WRITEABLE', etc.
| flat : numpy.flatiter object
| Flattened version of the array as an iterator. The iterator
| allows assignments, e.g., ``x.flat = 3`` (See `ndarray.flat` for
| assignment examples; TODO).
| imag : ndarray
| Imaginary part of the array.
| real : ndarray
| Real part of the array.
| size : int
| Number of elements in the array.
| itemsize : int
| The memory use of each array element in bytes.
| nbytes : int
| The total number of bytes required to store the array data,
| i.e., ``itemsize * size``.
| ndim : int
| The array's number of dimensions.
| shape : tuple of ints
| Shape of the array.
| strides : tuple of ints
| The step-size required to move from one element to the next in
| memory. For example, a contiguous ``(3, 4)`` array of type
| ``int16`` in C-order has strides ``(8, 2)``. This implies that
| to move from element to element in memory requires jumps of 2 bytes.
| To move from row-to-row, one needs to jump 8 bytes at a time
| (``2 * 4``).
| ctypes : ctypes object
| Class containing properties of the array needed for interaction
| with ctypes.
| base : ndarray
| If the array is a view into another array, that array is its `base`
| (unless that array is also a view). The `base` array is where the
| array data is actually stored.
|
| 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 :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| Notes
| -----
| There are two modes of creating an array using ``__new__``:
|
| 1. If `buffer` is None, then only `shape`, `dtype`, and `order`
| are used.
| 2. 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:
|
| >>> import numpy as np
| >>> 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])
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| a.__array__([dtype], *, copy=None)
|
| For ``dtype`` parameter it returns a new reference to self if
| ``dtype`` is not given or it matches array's data type.
| A new array of provided data type is returned if ``dtype``
| is different from the current data type of the array.
| For ``copy`` parameter it returns a new reference to self if
| ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| parameter. The method returns a new array for ``copy=True``, regardless of
| ``dtype`` parameter.
|
| A more detailed explanation of the ``__array__`` interface
| can be found in :ref:`dunder_array.interface`.
|
| __array_finalize__(...)
| a.__array_finalize__(obj, /)
|
| Present so subclasses can call super. Does nothing.
|
| __array_function__(...)
|
| __array_namespace__(...)
|
| __array_ufunc__(...)
|
| __array_wrap__(...)
| a.__array_wrap__(array[, context], /)
|
| Returns a view of `array` with the same type as self.
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __complex__(...)
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __copy__(...)
| a.__copy__()
|
| Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
|
| Equivalent to ``a.copy(order='K')``.
|
| __deepcopy__(...)
| a.__deepcopy__(memo, /)
|
| Used if :func:`copy.deepcopy` is called on an array.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __dlpack__(...)
| a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
|
| DLPack Protocol: Part of the Array API.
|
| __dlpack_device__(...)
| a.__dlpack_device__()
|
| DLPack Protocol: Part of the Array API.
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Return self+=value.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __ifloordiv__(self, value, /)
| Return self//=value.
|
| __ilshift__(self, value, /)
| Return self<<=value.
|
| __imatmul__(self, value, /)
| Return self@=value.
|
| __imod__(self, value, /)
| Return self%=value.
|
| __imul__(self, value, /)
| Return self*=value.
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __ior__(self, value, /)
| Return self|=value.
|
| __ipow__(self, value, /)
| Return self**=value.
|
| __irshift__(self, value, /)
| Return self>>=value.
|
| __isub__(self, value, /)
| Return self-=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __itruediv__(self, value, /)
| Return self/=value.
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __matmul__(self, value, /)
| Return self@value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| a.__reduce__()
|
| For pickling.
|
| __reduce_ex__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmatmul__(self, value, /)
| Return value@self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __setstate__(...)
| a.__setstate__(state, /)
|
| For unpickling.
|
| The `state` argument must be a sequence that contains the following
| elements:
|
| Parameters
| ----------
| version : int
| optional pickle version. If omitted defaults to 0.
| shape : tuple
| dtype : data-type
| isFortran : bool
| rawdata : string or list
| a binary string with the data (or a list if 'a' is an object array)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| a.all(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if all elements evaluate to True.
|
| Refer to `numpy.all` for full documentation.
|
| See Also
| --------
| numpy.all : equivalent function
|
| any(...)
| a.any(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if any of the elements of `a` evaluate to True.
|
| Refer to `numpy.any` for full documentation.
|
| See Also
| --------
| numpy.any : equivalent function
|
| argmax(...)
| a.argmax(axis=None, out=None, *, keepdims=False)
|
| Return indices of the maximum values along the given axis.
|
| Refer to `numpy.argmax` for full documentation.
|
| See Also
| --------
| numpy.argmax : equivalent function
|
| argmin(...)
| a.argmin(axis=None, out=None, *, keepdims=False)
|
| Return indices of the minimum values along the given axis.
|
| Refer to `numpy.argmin` for detailed documentation.
|
| See Also
| --------
| numpy.argmin : equivalent function
|
| argpartition(...)
| a.argpartition(kth, axis=-1, kind='introselect', order=None)
|
| Returns the indices that would partition this array.
|
| Refer to `numpy.argpartition` for full documentation.
|
| .. versionadded:: 1.8.0
|
| See Also
| --------
| numpy.argpartition : equivalent function
|
| argsort(...)
| a.argsort(axis=-1, kind=None, order=None)
|
| Returns the indices that would sort this array.
|
| Refer to `numpy.argsort` for full documentation.
|
| See Also
| --------
| numpy.argsort : equivalent function
|
| astype(...)
| a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
|
| Copy of the array, cast to a specified type.
|
| Parameters
| ----------
| dtype : str or dtype
| Typecode or data-type to which the array is cast.
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout order of the result.
| '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.
| Default is 'K'.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'unsafe'
| for backwards compatibility.
|
| * '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.
| subok : bool, optional
| If True, then sub-classes will be passed-through (default), otherwise
| the returned array will be forced to be a base-class array.
| copy : bool, optional
| By default, astype always returns a newly allocated array. If this
| is set to false, and the `dtype`, `order`, and `subok`
| requirements are satisfied, the input array is returned instead
| of a copy.
|
| Returns
| -------
| arr_t : ndarray
| Unless `copy` is False and the other conditions for returning the input
| array are satisfied (see description for `copy` input parameter), `arr_t`
| is a new array of the same shape as the input array, with dtype, order
| given by `dtype`, `order`.
|
| Notes
| -----
| .. versionchanged:: 1.17.0
| Casting between a simple data type and a structured one is possible only
| for "unsafe" casting. Casting to multiple fields is allowed, but
| casting from multiple fields is not.
|
| .. versionchanged:: 1.9.0
| Casting from numeric to string types in 'safe' casting mode requires
| that the string dtype length is long enough to store the max
| integer/float value converted.
|
| Raises
| ------
| ComplexWarning
| When casting from complex to float or int. To avoid this,
| one should use ``a.real.astype(t)``.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 2.5])
| >>> x
| array([1. , 2. , 2.5])
|
| >>> x.astype(int)
| array([1, 2, 2])
|
| byteswap(...)
| a.byteswap(inplace=False)
|
| Swap the bytes of the array elements
|
| Toggle between low-endian and big-endian data representation by
| returning a byteswapped array, optionally swapped in-place.
| Arrays of byte-strings are not swapped. The real and imaginary
| parts of a complex number are swapped individually.
|
| Parameters
| ----------
| inplace : bool, optional
| If ``True``, swap bytes in-place, default is ``False``.
|
| Returns
| -------
| out : ndarray
| The byteswapped array. If `inplace` is ``True``, this is
| a view to self.
|
| Examples
| --------
| >>> import numpy as np
| >>> A = np.array([1, 256, 8755], dtype=np.int16)
| >>> list(map(hex, A))
| ['0x1', '0x100', '0x2233']
| >>> A.byteswap(inplace=True)
| array([ 256, 1, 13090], dtype=int16)
| >>> list(map(hex, A))
| ['0x100', '0x1', '0x3322']
|
| Arrays of byte-strings are not swapped
|
| >>> A = np.array([b'ceg', b'fac'])
| >>> A.byteswap()
| array([b'ceg', b'fac'], dtype='|S3')
|
| ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| the same values but different representation in memory
|
| >>> A = np.array([1, 2, 3])
| >>> A.view(np.uint8)
| array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| 0, 0], dtype=uint8)
| >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| array([1, 2, 3])
| >>> A.view(np.uint8)
| array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| 0, 3], dtype=uint8)
|
| choose(...)
| a.choose(choices, out=None, mode='raise')
|
| Use an index array to construct a new array from a set of choices.
|
| Refer to `numpy.choose` for full documentation.
|
| See Also
| --------
| numpy.choose : equivalent function
|
| clip(...)
| a.clip(min=None, max=None, out=None, **kwargs)
|
| Return an array whose values are limited to ``[min, max]``.
| One of max or min must be given.
|
| Refer to `numpy.clip` for full documentation.
|
| See Also
| --------
| numpy.clip : equivalent function
|
| compress(...)
| a.compress(condition, axis=None, out=None)
|
| Return selected slices of this array along given axis.
|
| Refer to `numpy.compress` for full documentation.
|
| See Also
| --------
| numpy.compress : equivalent function
|
| conj(...)
| a.conj()
|
| Complex-conjugate all elements.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| conjugate(...)
| a.conjugate()
|
| Return the complex conjugate, element-wise.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| copy(...)
| a.copy(order='C')
|
| Return a copy of the array.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout of the copy. 'C' means C-order,
| 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| 'C' otherwise. 'K' means match the layout of `a` as closely
| as possible. (Note that this function and :func:`numpy.copy` are very
| similar but have different default values for their order=
| arguments, and this function always passes sub-classes through.)
|
| See also
| --------
| numpy.copy : Similar function with different default behavior
| numpy.copyto
|
| Notes
| -----
| This function is the preferred method for creating an array copy. The
| function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| and will not pass sub-classes through by default.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[1,2,3],[4,5,6]], order='F')
|
| >>> y = x.copy()
|
| >>> x.fill(0)
|
| >>> x
| array([[0, 0, 0],
| [0, 0, 0]])
|
| >>> y
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> y.flags['C_CONTIGUOUS']
| True
|
| For arrays containing Python objects (e.g. dtype=object),
| the copy is a shallow one. The new array will contain the
| same object which may lead to surprises if that object can
| be modified (is mutable):
|
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> b = a.copy()
| >>> b[2][0] = 10
| >>> a
| array([1, 'm', list([10, 3, 4])], dtype=object)
|
| To ensure all elements within an ``object`` array are copied,
| use `copy.deepcopy`:
|
| >>> import copy
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> c = copy.deepcopy(a)
| >>> c[2][0] = 10
| >>> c
| array([1, 'm', list([10, 3, 4])], dtype=object)
| >>> a
| array([1, 'm', list([2, 3, 4])], dtype=object)
|
| cumprod(...)
| a.cumprod(axis=None, dtype=None, out=None)
|
| Return the cumulative product of the elements along the given axis.
|
| Refer to `numpy.cumprod` for full documentation.
|
| See Also
| --------
| numpy.cumprod : equivalent function
|
| cumsum(...)
| a.cumsum(axis=None, dtype=None, out=None)
|
| Return the cumulative sum of the elements along the given axis.
|
| Refer to `numpy.cumsum` for full documentation.
|
| See Also
| --------
| numpy.cumsum : equivalent function
|
| diagonal(...)
| a.diagonal(offset=0, axis1=0, axis2=1)
|
| Return specified diagonals. In NumPy 1.9 the returned array is a
| read-only view instead of a copy as in previous NumPy versions. In
| a future version the read-only restriction will be removed.
|
| Refer to :func:`numpy.diagonal` for full documentation.
|
| See Also
| --------
| numpy.diagonal : equivalent function
|
| dot(...)
|
| dump(...)
| a.dump(file)
|
| Dump a pickle of the array to the specified file.
| The array can be read back with pickle.load or numpy.load.
|
| Parameters
| ----------
| file : str or Path
| A string naming the dump file.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| dumps(...)
| a.dumps()
|
| Returns the pickle of the array as a string.
| pickle.loads will convert the string back to an array.
|
| Parameters
| ----------
| None
|
| fill(...)
| a.fill(value)
|
| Fill the array with a scalar value.
|
| Parameters
| ----------
| value : scalar
| All elements of `a` will be assigned this value.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([1, 2])
| >>> a.fill(0)
| >>> a
| array([0, 0])
| >>> a = np.empty(2)
| >>> a.fill(1)
| >>> a
| array([1., 1.])
|
| Fill expects a scalar value and always behaves the same as assigning
| to a single array element. The following is a rare example where this
| distinction is important:
|
| >>> a = np.array([None, None], dtype=object)
| >>> a[0] = np.array(3)
| >>> a
| array([array(3), None], dtype=object)
| >>> a.fill(np.array(3))
| >>> a
| array([array(3), array(3)], dtype=object)
|
| Where other forms of assignments will unpack the array being assigned:
|
| >>> a[...] = np.array(3)
| >>> a
| array([3, 3], dtype=object)
|
| flatten(...)
| a.flatten(order='C')
|
| Return a copy of the array collapsed into one dimension.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| 'C' means to flatten in row-major (C-style) order.
| 'F' means to flatten in column-major (Fortran-
| style) order. 'A' means to flatten in column-major
| order if `a` is Fortran *contiguous* in memory,
| row-major order otherwise. 'K' means to flatten
| `a` in the order the elements occur in memory.
| The default is 'C'.
|
| Returns
| -------
| y : ndarray
| A copy of the input array, flattened to one dimension.
|
| See Also
| --------
| ravel : Return a flattened array.
| flat : A 1-D flat iterator over the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,2], [3,4]])
| >>> a.flatten()
| array([1, 2, 3, 4])
| >>> a.flatten('F')
| array([1, 3, 2, 4])
|
| getfield(...)
| a.getfield(dtype, offset=0)
|
| Returns a field of the given array as a certain type.
|
| A field is a view of the array data with a given data-type. The values in
| the view are determined by the given type and the offset into the current
| array in bytes. The offset needs to be such that the view dtype fits in the
| array dtype; for example an array of dtype complex128 has 16-byte elements.
| If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| between 0 and 12 bytes.
|
| Parameters
| ----------
| dtype : str or dtype
| The data type of the view. The dtype size of the view can not be larger
| than that of the array itself.
| offset : int
| Number of bytes to skip before beginning the element view.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.diag([1.+1.j]*2)
| >>> x[1, 1] = 2 + 4.j
| >>> x
| array([[1.+1.j, 0.+0.j],
| [0.+0.j, 2.+4.j]])
| >>> x.getfield(np.float64)
| array([[1., 0.],
| [0., 2.]])
|
| By choosing an offset of 8 bytes we can select the complex part of the
| array for our view:
|
| >>> x.getfield(np.float64, offset=8)
| array([[1., 0.],
| [0., 4.]])
|
| item(...)
| a.item(*args)
|
| Copy an element of an array to a standard Python scalar and return it.
|
| Parameters
| ----------
| \*args : Arguments (variable number and type)
|
| * none: in this case, the method only works for arrays
| with one element (`a.size == 1`), which element is
| copied into a standard Python scalar object and returned.
|
| * int_type: this argument is interpreted as a flat index into
| the array, specifying which element to copy and return.
|
| * tuple of int_types: functions as does a single int_type argument,
| except that the argument is interpreted as an nd-index into the
| array.
|
| Returns
| -------
| z : Standard Python scalar object
| A copy of the specified element of the array as a suitable
| Python scalar
|
| Notes
| -----
| When the data type of `a` is longdouble or clongdouble, item() returns
| a scalar array object because there is no available Python scalar that
| would not lose information. Void arrays return a buffer object for item(),
| unless fields are defined, in which case a tuple is returned.
|
| `item` is very similar to a[args], except, instead of an array scalar,
| a standard Python scalar is returned. This can be useful for speeding up
| access to elements of the array and doing arithmetic on elements of the
| array using Python's optimized math.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.random.seed(123)
| >>> x = np.random.randint(9, size=(3, 3))
| >>> x
| array([[2, 2, 6],
| [1, 3, 6],
| [1, 0, 1]])
| >>> x.item(3)
| 1
| >>> x.item(7)
| 0
| >>> x.item((0, 1))
| 2
| >>> x.item((2, 2))
| 1
|
| For an array with object dtype, elements are returned as-is.
|
| >>> a = np.array([np.int64(1)], dtype=object)
| >>> a.item() #return np.int64
| np.int64(1)
|
| max(...)
| a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the maximum along a given axis.
|
| Refer to `numpy.amax` for full documentation.
|
| See Also
| --------
| numpy.amax : equivalent function
|
| mean(...)
| a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
|
| Returns the average of the array elements along given axis.
|
| Refer to `numpy.mean` for full documentation.
|
| See Also
| --------
| numpy.mean : equivalent function
|
| min(...)
| a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the minimum along a given axis.
|
| Refer to `numpy.amin` for full documentation.
|
| See Also
| --------
| numpy.amin : equivalent function
|
| nonzero(...)
| a.nonzero()
|
| Return the indices of the elements that are non-zero.
|
| Refer to `numpy.nonzero` for full documentation.
|
| See Also
| --------
| numpy.nonzero : equivalent function
|
| partition(...)
| a.partition(kth, axis=-1, kind='introselect', order=None)
|
| Partially sorts the elements in the array 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. In the output array, all elements smaller than the k-th element
| are located to the left of this element and all equal or greater are
| located to its right. The ordering of the elements in the two partitions
| on the either side of the k-th element in the output array is undefined.
|
| .. versionadded:: 1.8.0
|
| Parameters
| ----------
| kth : int or sequence of ints
| Element index to partition by. The kth element value 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 kth it will partition all elements
| indexed by kth of them into their sorted position at once.
|
| .. deprecated:: 1.22.0
| Passing booleans as index is deprecated.
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'introselect'}, optional
| Selection algorithm. Default is 'introselect'.
| order : str 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, and not all fields need to be specified,
| but unspecified fields will still be used, in the order in which
| they come up in the dtype, to break ties.
|
| See Also
| --------
| numpy.partition : Return a partitioned copy of an array.
| argpartition : Indirect partition.
| sort : Full sort.
|
| Notes
| -----
| See ``np.partition`` for notes on the different algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([3, 4, 2, 1])
| >>> a.partition(3)
| >>> a
| array([2, 1, 3, 4]) # may vary
|
| >>> a.partition((1, 3))
| >>> a
| array([1, 2, 3, 4])
|
| prod(...)
| a.prod(axis=None, dtype=None, out=None, keepdims=False,
| initial=1, where=True)
|
| Return the product of the array elements over the given axis
|
| Refer to `numpy.prod` for full documentation.
|
| See Also
| --------
| numpy.prod : equivalent function
|
| put(...)
| a.put(indices, values, mode='raise')
|
| Set ``a.flat[n] = values[n]`` for all `n` in indices.
|
| Refer to `numpy.put` for full documentation.
|
| See Also
| --------
| numpy.put : equivalent function
|
| ravel(...)
| a.ravel([order])
|
| Return a flattened array.
|
| Refer to `numpy.ravel` for full documentation.
|
| See Also
| --------
| numpy.ravel : equivalent function
|
| ndarray.flat : a flat iterator on the array.
|
| repeat(...)
| a.repeat(repeats, axis=None)
|
| Repeat elements of an array.
|
| Refer to `numpy.repeat` for full documentation.
|
| See Also
| --------
| numpy.repeat : equivalent function
|
| reshape(...)
| a.reshape(shape, /, *, order='C', copy=None)
|
| Returns an array containing the same data with a new shape.
|
| Refer to `numpy.reshape` for full documentation.
|
| See Also
| --------
| numpy.reshape : equivalent function
|
| Notes
| -----
| Unlike the free function `numpy.reshape`, this method on `ndarray` allows
| the elements of the shape parameter to be passed in as separate arguments.
| For example, ``a.reshape(10, 11)`` is equivalent to
| ``a.reshape((10, 11))``.
|
| resize(...)
| a.resize(new_shape, refcheck=True)
|
| Change shape and size of array in-place.
|
| Parameters
| ----------
| new_shape : tuple of ints, or `n` ints
| Shape of resized array.
| refcheck : bool, optional
| If False, reference count will not be checked. Default is True.
|
| Returns
| -------
| None
|
| Raises
| ------
| ValueError
| If `a` does not own its own data or references or views to it exist,
| and the data memory must be changed.
| PyPy only: will always raise if the data memory must be changed, since
| there is no reliable way to determine if references or views to it
| exist.
|
| SystemError
| If the `order` keyword argument is specified. This behaviour is a
| bug in NumPy.
|
| See Also
| --------
| resize : Return a new array with the specified shape.
|
| Notes
| -----
| This reallocates space for the data area if necessary.
|
| Only contiguous arrays (data elements consecutive in memory) can be
| resized.
|
| The purpose of the reference count check is to make sure you
| do not use this array as a buffer for another Python object and then
| reallocate the memory. However, reference counts can increase in
| other ways so if you are sure that you have not shared the memory
| for this array with another Python object, then you may safely set
| `refcheck` to False.
|
| Examples
| --------
| Shrinking an array: array is flattened (in the order that the data are
| stored in memory), resized, and reshaped:
|
| >>> import numpy as np
|
| >>> a = np.array([[0, 1], [2, 3]], order='C')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [1]])
|
| >>> a = np.array([[0, 1], [2, 3]], order='F')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [2]])
|
| Enlarging an array: as above, but missing entries are filled with zeros:
|
| >>> b = np.array([[0, 1], [2, 3]])
| >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
| >>> b
| array([[0, 1, 2],
| [3, 0, 0]])
|
| Referencing an array prevents resizing...
|
| >>> c = a
| >>> a.resize((1, 1))
| Traceback (most recent call last):
| ...
| ValueError: cannot resize an array that references or is referenced ...
|
| Unless `refcheck` is False:
|
| >>> a.resize((1, 1), refcheck=False)
| >>> a
| array([[0]])
| >>> c
| array([[0]])
|
| round(...)
| a.round(decimals=0, out=None)
|
| Return `a` with each element rounded to the given number of decimals.
|
| Refer to `numpy.around` for full documentation.
|
| See Also
| --------
| numpy.around : equivalent function
|
| searchsorted(...)
| a.searchsorted(v, side='left', sorter=None)
|
| Find indices where elements of v should be inserted in a to maintain order.
|
| For full documentation, see `numpy.searchsorted`
|
| See Also
| --------
| numpy.searchsorted : equivalent function
|
| setfield(...)
| a.setfield(val, dtype, offset=0)
|
| Put a value into a specified place in a field defined by a data-type.
|
| Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| bytes into the field.
|
| Parameters
| ----------
| val : object
| Value to be placed in field.
| dtype : dtype object
| Data-type of the field in which to place `val`.
| offset : int, optional
| The number of bytes into the field at which to place `val`.
|
| Returns
| -------
| None
|
| See Also
| --------
| getfield
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.eye(3)
| >>> x.getfield(np.float64)
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
| >>> x.setfield(3, np.int32)
| >>> x.getfield(np.int32)
| array([[3, 3, 3],
| [3, 3, 3],
| [3, 3, 3]], dtype=int32)
| >>> x
| array([[1.0e+000, 1.5e-323, 1.5e-323],
| [1.5e-323, 1.0e+000, 1.5e-323],
| [1.5e-323, 1.5e-323, 1.0e+000]])
| >>> x.setfield(np.eye(3), np.int32)
| >>> x
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
|
| setflags(...)
| a.setflags(write=None, align=None, uic=None)
|
| Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| respectively.
|
| These Boolean-valued flags affect how numpy interprets the memory
| area used by `a` (see Notes below). The ALIGNED flag can only
| be set to True if the data is actually aligned according to the type.
| The WRITEBACKIFCOPY flag can never be set
| to True. The flag WRITEABLE can only be set to True if the array owns its
| own memory, or the ultimate owner of the memory exposes a writeable buffer
| interface, or is a string. (The exception for string is made so that
| unpickling can be done without copying memory.)
|
| Parameters
| ----------
| write : bool, optional
| Describes whether or not `a` can be written to.
| align : bool, optional
| Describes whether or not `a` is aligned properly for its type.
| uic : bool, optional
| Describes whether or not `a` is a copy of another "base" array.
|
| Notes
| -----
| Array flags provide information about how the memory area used
| for the array is to be interpreted. There are 7 Boolean flags
| in use, only three of which can be changed by the user:
| WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
|
| WRITEABLE (W) the data area can be written to;
|
| ALIGNED (A) the data and strides are aligned appropriately for the hardware
| (as determined by the compiler);
|
| WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| called, the base array will be updated with the contents of this array.
|
| All flags can be accessed using the single (upper case) letter as well
| as the full name.
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.array([[3, 1, 7],
| ... [2, 0, 0],
| ... [8, 5, 9]])
| >>> y
| array([[3, 1, 7],
| [2, 0, 0],
| [8, 5, 9]])
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
| >>> y.setflags(write=0, align=0)
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : False
| ALIGNED : False
| WRITEBACKIFCOPY : False
| >>> y.setflags(uic=1)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: cannot set WRITEBACKIFCOPY flag to True
|
| sort(...)
| a.sort(axis=-1, kind=None, order=None)
|
| Sort an array in-place. Refer to `numpy.sort` for full documentation.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
| and 'mergesort' use timsort under the covers and, in general, the
| actual implementation will vary with datatype. The 'mergesort' option
| is retained for backwards compatibility.
|
| .. versionchanged:: 1.15.0
| The 'stable' option was added.
|
| order : str 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, and 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.
|
| See Also
| --------
| numpy.sort : Return a sorted copy of an array.
| numpy.argsort : Indirect sort.
| numpy.lexsort : Indirect stable sort on multiple keys.
| numpy.searchsorted : Find elements in sorted array.
| numpy.partition: Partial sort.
|
| Notes
| -----
| See `numpy.sort` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,4], [3,1]])
| >>> a.sort(axis=1)
| >>> a
| array([[1, 4],
| [1, 3]])
| >>> a.sort(axis=0)
| >>> a
| array([[1, 3],
| [1, 4]])
|
| Use the `order` keyword to specify a field to use when sorting a
| structured array:
|
| >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
| >>> a.sort(order='y')
| >>> a
| array([(b'c', 1), (b'a', 2)],
| dtype=[('x', 'S1'), ('y', '<i8')])
|
| squeeze(...)
| a.squeeze(axis=None)
|
| Remove axes of length one from `a`.
|
| Refer to `numpy.squeeze` for full documentation.
|
| See Also
| --------
| numpy.squeeze : equivalent function
|
| std(...)
| a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the standard deviation of the array elements along given axis.
|
| Refer to `numpy.std` for full documentation.
|
| See Also
| --------
| numpy.std : equivalent function
|
| sum(...)
| a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
|
| Return the sum of the array elements over the given axis.
|
| Refer to `numpy.sum` for full documentation.
|
| See Also
| --------
| numpy.sum : equivalent function
|
| swapaxes(...)
| a.swapaxes(axis1, axis2)
|
| Return a view of the array with `axis1` and `axis2` interchanged.
|
| Refer to `numpy.swapaxes` for full documentation.
|
| See Also
| --------
| numpy.swapaxes : equivalent function
|
| take(...)
| a.take(indices, axis=None, out=None, mode='raise')
|
| Return an array formed from the elements of `a` at the given indices.
|
| Refer to `numpy.take` for full documentation.
|
| See Also
| --------
| numpy.take : equivalent function
|
| to_device(...)
|
| tobytes(...)
| a.tobytes(order='C')
|
| Construct Python bytes containing the raw data bytes in the array.
|
| Constructs Python bytes showing a copy of the raw contents of
| data memory. The bytes object is produced in C-order by default.
| This behavior is controlled by the ``order`` parameter.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| order : {'C', 'F', 'A'}, optional
| Controls the memory layout of the bytes object. 'C' means C-order,
| 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
| Fortran contiguous, 'C' otherwise. Default is 'C'.
|
| Returns
| -------
| s : bytes
| Python bytes exhibiting a copy of `a`'s raw data.
|
| See also
| --------
| frombuffer
| Inverse of this operation, construct a 1-dimensional array from Python
| bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
| >>> x.tobytes()
| b'\x00\x00\x01\x00\x02\x00\x03\x00'
| >>> x.tobytes('C') == x.tobytes()
| True
| >>> x.tobytes('F')
| b'\x00\x00\x02\x00\x01\x00\x03\x00'
|
| tofile(...)
| a.tofile(fid, sep="", format="%s")
|
| Write array to a file as text or binary (default).
|
| Data is always written in 'C' order, independent of the order of `a`.
| The data produced by this method can be recovered using the function
| fromfile().
|
| Parameters
| ----------
| fid : file or str or Path
| An open file object, or a string containing a filename.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| sep : str
| Separator between array items for text output.
| If "" (empty), a binary file is written, equivalent to
| ``file.write(a.tobytes())``.
| format : str
| Format string for text file output.
| Each entry in the array is formatted to text by first converting
| it to the closest Python type, and then using "format" % item.
|
| Notes
| -----
| This is a convenience function for quick storage of array data.
| Information on endianness and precision is lost, so this method is not a
| good choice for files intended to archive data or transport data between
| machines with different endianness. Some of these problems can be overcome
| by outputting the data as text files, at the expense of speed and file
| size.
|
| When fid is a file object, array contents are directly written to the
| file, bypassing the file object's ``write`` method. As a result, tofile
| cannot be used with files objects supporting compression (e.g., GzipFile)
| or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
|
| tolist(...)
| a.tolist()
|
| Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
|
| Return a copy of the array data as a (nested) Python list.
| Data items are converted to the nearest compatible builtin Python type, via
| the `~numpy.ndarray.item` function.
|
| If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
| not be a list at all, but a simple Python scalar.
|
| Parameters
| ----------
| none
|
| Returns
| -------
| y : object, or list of object, or list of list of object, or ...
| The possibly nested list of array elements.
|
| Notes
| -----
| The array may be recreated via ``a = np.array(a.tolist())``, although this
| may sometimes lose precision.
|
| Examples
| --------
| For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
| except that ``tolist`` changes numpy scalars to Python scalars:
|
| >>> import numpy as np
| >>> a = np.uint32([1, 2])
| >>> a_list = list(a)
| >>> a_list
| [1, 2]
| >>> type(a_list[0])
| <class 'numpy.uint32'>
| >>> a_tolist = a.tolist()
| >>> a_tolist
| [1, 2]
| >>> type(a_tolist[0])
| <class 'int'>
|
| Additionally, for a 2D array, ``tolist`` applies recursively:
|
| >>> a = np.array([[1, 2], [3, 4]])
| >>> list(a)
| [array([1, 2]), array([3, 4])]
| >>> a.tolist()
| [[1, 2], [3, 4]]
|
| The base case for this recursion is a 0D array:
|
| >>> a = np.array(1)
| >>> list(a)
| Traceback (most recent call last):
| ...
| TypeError: iteration over a 0-d array
| >>> a.tolist()
| 1
|
| tostring(...)
| a.tostring(order='C')
|
| A compatibility alias for `~ndarray.tobytes`, with exactly the same
| behavior.
|
| Despite its name, it returns :class:`bytes` not :class:`str`\ s.
|
| .. deprecated:: 1.19.0
|
| trace(...)
| a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
|
| Return the sum along diagonals of the array.
|
| Refer to `numpy.trace` for full documentation.
|
| See Also
| --------
| numpy.trace : equivalent function
|
| transpose(...)
| a.transpose(*axes)
|
| Returns a view of the array with axes transposed.
|
| Refer to `numpy.transpose` for full documentation.
|
| Parameters
| ----------
| axes : None, tuple of ints, or `n` ints
|
| * None or no argument: reverses the order of the axes.
|
| * tuple of ints: `i` in the `j`-th place in the tuple means that the
| array's `i`-th axis becomes the transposed array's `j`-th axis.
|
| * `n` ints: same as an n-tuple of the same ints (this form is
| intended simply as a "convenience" alternative to the tuple form).
|
| Returns
| -------
| p : ndarray
| View of the array with its axes suitably permuted.
|
| See Also
| --------
| transpose : Equivalent function.
| ndarray.T : Array property returning the array transposed.
| ndarray.reshape : Give a new shape to an array without changing its data.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.transpose()
| array([[1, 3],
| [2, 4]])
| >>> a.transpose((1, 0))
| array([[1, 3],
| [2, 4]])
| >>> a.transpose(1, 0)
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.transpose()
| array([1, 2, 3, 4])
|
| var(...)
| a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the variance of the array elements, along given axis.
|
| Refer to `numpy.var` for full documentation.
|
| See Also
| --------
| numpy.var : equivalent function
|
| view(...)
| a.view([dtype][, type])
|
| New view of array with the same data.
|
| .. note::
| Passing None for ``dtype`` is different from omitting the parameter,
| since the former invokes ``dtype(None)`` which is an alias for
| ``dtype('float64')``.
|
| Parameters
| ----------
| dtype : data-type or ndarray sub-class, optional
| Data-type descriptor of the returned view, e.g., float32 or int16.
| Omitting it results in the view having the same data-type as `a`.
| This argument can also be specified as an ndarray sub-class, which
| then specifies the type of the returned object (this is equivalent to
| setting the ``type`` parameter).
| type : Python type, optional
| Type of the returned view, e.g., ndarray or matrix. Again, omission
| of the parameter results in type preservation.
|
| Notes
| -----
| ``a.view()`` is used two different ways:
|
| ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| of the array's memory with a different data-type. This can cause a
| reinterpretation of the bytes of memory.
|
| ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| returns an instance of `ndarray_subclass` that looks at the same array
| (same shape, dtype, etc.) This does not cause a reinterpretation of the
| memory.
|
| For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| bytes per entry than the previous dtype (for example, converting a regular
| array to a structured array), then the last axis of ``a`` must be
| contiguous. This axis will be resized in the result.
|
| .. versionchanged:: 1.23.0
| Only the last axis needs to be contiguous. Previously, the entire array
| had to be C-contiguous.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
|
| Viewing array data using a different type and dtype:
|
| >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
| >>> y = x.view(dtype=nonneg, type=np.recarray)
| >>> x["a"]
| array([-1], dtype=int8)
| >>> y.a
| array([255], dtype=uint8)
|
| Creating a view on a structured array so it can be used in calculations
|
| >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
| >>> xv = x.view(dtype=np.int8).reshape(-1,2)
| >>> xv
| array([[1, 2],
| [3, 4]], dtype=int8)
| >>> xv.mean(0)
| array([2., 3.])
|
| Making changes to the view changes the underlying array
|
| >>> xv[0,1] = 20
| >>> x
| array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
|
| Using a view to convert an array to a recarray:
|
| >>> z = x.view(np.recarray)
| >>> z.a
| array([1, 3], dtype=int8)
|
| Views share data:
|
| >>> x[0] = (9, 10)
| >>> z[0]
| np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
|
| Views that change the dtype size (bytes per entry) should normally be
| avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
|
| >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
| >>> y = x[:, ::2]
| >>> y
| array([[1, 3],
| [4, 6]], dtype=int16)
| >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
| Traceback (most recent call last):
| ...
| ValueError: To change to a dtype of a different size, the last axis must be contiguous
| >>> z = y.copy()
| >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
| array([[(1, 3)],
| [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
|
| However, views that change dtype are totally fine for arrays with a
| contiguous last axis, even if the rest of the axes are not C-contiguous:
|
| >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
| >>> x.transpose(1, 0, 2).view(np.int16)
| array([[[ 256, 770],
| [3340, 3854]],
| <BLANKLINE>
| [[1284, 1798],
| [4368, 4882]],
| <BLANKLINE>
| [[2312, 2826],
| [5396, 5910]]], dtype=int16)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| a.__class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.ndarray` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.ndarray` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.ndarray[Any, np.dtype[Any]]
| numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
| numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| T
| View of the transposed array.
|
| Same as ``self.transpose()``.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.T
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.T
| array([1, 2, 3, 4])
|
| See Also
| --------
| transpose
|
| __array_interface__
| Array protocol: Python side.
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: C-struct side.
|
| base
| Base object if memory is from some other object.
|
| Examples
| --------
| The base of an array that owns its memory is None:
|
| >>> import numpy as np
| >>> x = np.array([1,2,3,4])
| >>> x.base is None
| True
|
| Slicing creates a view, whose memory is shared with x:
|
| >>> y = x[2:]
| >>> y.base is x
| True
|
| ctypes
| An object to simplify the interaction of the array with the ctypes
| module.
|
| This attribute creates an object that makes it easier to use arrays
| when calling shared libraries with the ctypes module. The returned
| object has, among others, data, shape, and strides attributes (see
| Notes below) which themselves return ctypes objects that can be used
| as arguments to a shared library.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| c : Python object
| Possessing attributes data, shape, strides, etc.
|
| See Also
| --------
| numpy.ctypeslib
|
| Notes
| -----
| Below are the public attributes of this object which were documented
| in "Guide to NumPy" (we have omitted undocumented public attributes,
| as well as documented private attributes):
|
| .. autoattribute:: numpy._core._internal._ctypes.data
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.shape
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.strides
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.data_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.shape_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.strides_as
| :noindex:
|
| If the ctypes module is not available, then the ctypes attribute
| of array objects still returns something useful, but ctypes objects
| are not returned and errors may be raised instead. In particular,
| the object will still have the ``as_parameter`` attribute which will
| return an integer equal to the data attribute.
|
| Examples
| --------
| >>> import numpy as np
| >>> import ctypes
| >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| >>> x
| array([[0, 1],
| [2, 3]], dtype=int32)
| >>> x.ctypes.data
| 31962608 # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| c_uint(0)
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| c_ulong(4294967296)
| >>> x.ctypes.shape
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| >>> x.ctypes.strides
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
|
| data
| Python buffer object pointing to the start of the array's data.
|
| device
|
| dtype
| Data-type of the array's elements.
|
| .. warning::
|
| Setting ``arr.dtype`` is discouraged and may be deprecated in the
| future. Setting will replace the ``dtype`` without modifying the
| memory (see also `ndarray.view` and `ndarray.astype`).
|
| Parameters
| ----------
| None
|
| Returns
| -------
| d : numpy dtype object
|
| See Also
| --------
| ndarray.astype : Cast the values contained in the array to a new data-type.
| ndarray.view : Create a view of the same data but a different data-type.
| numpy.dtype
|
| Examples
| --------
| >>> x
| array([[0, 1],
| [2, 3]])
| >>> x.dtype
| dtype('int32')
| >>> type(x.dtype)
| <type 'numpy.dtype'>
|
| flags
| Information about the memory layout of the array.
|
| Attributes
| ----------
| C_CONTIGUOUS (C)
| The data is in a single, C-style contiguous segment.
| F_CONTIGUOUS (F)
| The data is in a single, Fortran-style contiguous segment.
| OWNDATA (O)
| The array owns the memory it uses or borrows it from another object.
| WRITEABLE (W)
| The data area can be written to. Setting this to False locks
| the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| from its base array at creation time, but a view of a writeable
| array may be subsequently locked while the base array remains writeable.
| (The opposite is not true, in that a view of a locked array may not
| be made writeable. However, currently, locking a base object does not
| lock any views that already reference it, so under that circumstance it
| is possible to alter the contents of a locked array via a previously
| created writeable view onto it.) Attempting to change a non-writeable
| array raises a RuntimeError exception.
| ALIGNED (A)
| The data and all elements are aligned appropriately for the hardware.
| WRITEBACKIFCOPY (X)
| This array is a copy of some other array. The C-API function
| PyArray_ResolveWritebackIfCopy must be called before deallocating
| to the base array will be updated with the contents of this array.
| FNC
| F_CONTIGUOUS and not C_CONTIGUOUS.
| FORC
| F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| BEHAVED (B)
| ALIGNED and WRITEABLE.
| CARRAY (CA)
| BEHAVED and C_CONTIGUOUS.
| FARRAY (FA)
| BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
|
| Notes
| -----
| The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| names are only supported in dictionary access.
|
| Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| changed by the user, via direct assignment to the attribute or dictionary
| entry, or by calling `ndarray.setflags`.
|
| The array flags cannot be set arbitrarily:
|
| - WRITEBACKIFCOPY can only be set ``False``.
| - ALIGNED can only be set ``True`` if the data is truly aligned.
| - WRITEABLE can only be set ``True`` if the array owns its own memory
| or the ultimate owner of the memory exposes a writeable buffer
| interface or is a string.
|
| Arrays can be both C-style and Fortran-style contiguous simultaneously.
| This is clear for 1-dimensional arrays, but can also be true for higher
| dimensional arrays.
|
| Even for contiguous arrays a stride for a given dimension
| ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| or the array has no elements.
| It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| Fortran-style contiguous arrays is true.
|
| flat
| A 1-D iterator over the array.
|
| This is a `numpy.flatiter` instance, which acts similarly to, but is not
| a subclass of, Python's built-in iterator object.
|
| See Also
| --------
| flatten : Return a copy of the array collapsed into one dimension.
|
| flatiter
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(1, 7).reshape(2, 3)
| >>> x
| array([[1, 2, 3],
| [4, 5, 6]])
| >>> x.flat[3]
| 4
| >>> x.T
| array([[1, 4],
| [2, 5],
| [3, 6]])
| >>> x.T.flat[3]
| 5
| >>> type(x.flat)
| <class 'numpy.flatiter'>
|
| An assignment example:
|
| >>> x.flat = 3; x
| array([[3, 3, 3],
| [3, 3, 3]])
| >>> x.flat[[1,4]] = 1; x
| array([[3, 1, 3],
| [3, 1, 3]])
|
| imag
| The imaginary part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.imag
| array([ 0. , 0.70710678])
| >>> x.imag.dtype
| dtype('float64')
|
| itemset
|
| itemsize
| Length of one array element in bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1,2,3], dtype=np.float64)
| >>> x.itemsize
| 8
| >>> x = np.array([1,2,3], dtype=np.complex128)
| >>> x.itemsize
| 16
|
| mT
| View of the matrix transposed array.
|
| The matrix transpose is the transpose of the last two dimensions, even
| if the array is of higher dimension.
|
| .. versionadded:: 2.0
|
| Raises
| ------
| ValueError
| If the array is of dimension less than 2.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.mT
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.arange(8).reshape((2, 2, 2))
| >>> a
| array([[[0, 1],
| [2, 3]],
| <BLANKLINE>
| [[4, 5],
| [6, 7]]])
| >>> a.mT
| array([[[0, 2],
| [1, 3]],
| <BLANKLINE>
| [[4, 6],
| [5, 7]]])
|
| nbytes
| Total bytes consumed by the elements of the array.
|
| Notes
| -----
| Does not include memory consumed by non-element attributes of the
| array object.
|
| See Also
| --------
| sys.getsizeof
| Memory consumed by the object itself without parents in case view.
| This does include memory consumed by non-element attributes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3,5,2), dtype=np.complex128)
| >>> x.nbytes
| 480
| >>> np.prod(x.shape) * x.itemsize
| 480
|
| ndim
| Number of array dimensions.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3])
| >>> x.ndim
| 1
| >>> y = np.zeros((2, 3, 4))
| >>> y.ndim
| 3
|
| newbyteorder
|
| ptp
|
| real
| The real part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.real
| array([ 1. , 0.70710678])
| >>> x.real.dtype
| dtype('float64')
|
| See Also
| --------
| numpy.real : equivalent function
|
| shape
| Tuple of array dimensions.
|
| The shape property is usually used to get the current shape of an array,
| but may also be used to reshape the array in-place by assigning a tuple of
| array dimensions to it. As with `numpy.reshape`, one of the new shape
| dimensions can be -1, in which case its value is inferred from the size of
| the array and the remaining dimensions. Reshaping an array in-place will
| fail if a copy is required.
|
| .. warning::
|
| Setting ``arr.shape`` is discouraged and may be deprecated in the
| future. Using `ndarray.reshape` is the preferred approach.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3, 4])
| >>> x.shape
| (4,)
| >>> y = np.zeros((2, 3, 4))
| >>> y.shape
| (2, 3, 4)
| >>> y.shape = (3, 8)
| >>> y
| array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| >>> y.shape = (3, 6)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: total size of new array must be unchanged
| >>> np.zeros((4,2))[::2].shape = (-1,)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| AttributeError: Incompatible shape for in-place modification. Use
| `.reshape()` to make a copy with the desired shape.
|
| See Also
| --------
| numpy.shape : Equivalent getter function.
| numpy.reshape : Function similar to setting ``shape``.
| ndarray.reshape : Method similar to setting ``shape``.
|
| size
| Number of elements in the array.
|
| Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| dimensions.
|
| Notes
| -----
| `a.size` returns a standard arbitrary precision Python integer. This
| may not be the case with other methods of obtaining the same value
| (like the suggested ``np.prod(a.shape)``, which returns an instance
| of ``np.int_``), and may be relevant if the value is used further in
| calculations that may overflow a fixed size integer type.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| >>> x.size
| 30
| >>> np.prod(x.shape)
| 30
|
| strides
| Tuple of bytes to step in each dimension when traversing an array.
|
| The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| is::
|
| offset = sum(np.array(i) * a.strides)
|
| A more detailed explanation of strides can be found in
| :ref:`arrays.ndarray`.
|
| .. warning::
|
| Setting ``arr.strides`` is discouraged and may be deprecated in the
| future. `numpy.lib.stride_tricks.as_strided` should be preferred
| to create a new view of the same data in a safer way.
|
| Notes
| -----
| Imagine an array of 32-bit integers (each 4 bytes)::
|
| x = np.array([[0, 1, 2, 3, 4],
| [5, 6, 7, 8, 9]], dtype=np.int32)
|
| This array is stored in memory as 40 bytes, one after the other
| (known as a contiguous block of memory). The strides of an array tell
| us how many bytes we have to skip in memory to move to the next position
| along a certain axis. For example, we have to skip 4 bytes (1 value) to
| move to the next column, but 20 bytes (5 values) to get to the same
| position in the next row. As such, the strides for the array `x` will be
| ``(20, 4)``.
|
| See Also
| --------
| numpy.lib.stride_tricks.as_strided
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| >>> y
| array([[[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]],
| [[12, 13, 14, 15],
| [16, 17, 18, 19],
| [20, 21, 22, 23]]])
| >>> y.strides
| (48, 16, 4)
| >>> y[1,1,1]
| 17
| >>> offset=sum(y.strides * np.array((1,1,1)))
| >>> offset/y.itemsize
| 17
|
| >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| >>> x.strides
| (32, 4, 224, 1344)
| >>> i = np.array([3,5,2,2])
| >>> offset = sum(i * x.strides)
| >>> x[3,5,2,2]
| 813
| >>> offset / x.itemsize
| 813
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
numpy.ndenumerate
Python Library Documentation: class ndenumerate in module numpy class ndenumerate(builtins.object) | ndenumerate(arr) | | Multidimensional index iterator. | | Return an iterator yielding pairs of array coordinates and values. | | Parameters | ---------- | arr : ndarray | Input array. | | See Also | -------- | ndindex, flatiter | | Examples | -------- | >>> import numpy as np | >>> 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 | | Methods defined here: | | __init__(self, arr) from numpy.lib._index_tricks_impl.ndenumerate | Initialize self. See help(type(self)) for accurate signature. | | __iter__(self) from numpy.lib._index_tricks_impl.ndenumerate | | __next__(self) from numpy.lib._index_tricks_impl.ndenumerate | Standard iterator method, returns the index tuple and array value. | | Returns | ------- | coords : tuple of ints | The indices of the current iteration. | val : scalar | The array element of the current iteration. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
numpy.ndim
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
ndim(a)
Return the number of dimensions of an array.
Parameters
----------
a : array_like
Input array. If it is not already an ndarray, a conversion is
attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in `a`. Scalars are zero-dimensional.
See Also
--------
ndarray.ndim : equivalent method
shape : dimensions of array
ndarray.shape : dimensions of array
Examples
--------
>>> import numpy as np
>>> np.ndim([[1,2,3],[4,5,6]])
2
>>> np.ndim(np.array([[1,2,3],[4,5,6]]))
2
>>> np.ndim(1)
0
numpy.ndindex
Python Library Documentation: class ndindex in module numpy class ndindex(builtins.object) | ndindex(*shape) | | 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 | ---------- | shape : ints, 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 | -------- | >>> import numpy as np | | 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 defined here: | | __init__(self, *shape) from numpy.lib._index_tricks_impl.ndindex | Initialize self. See help(type(self)) for accurate signature. | | __iter__(self) from numpy.lib._index_tricks_impl.ndindex | | __next__(self) from numpy.lib._index_tricks_impl.ndindex | Standard iterator method, updates the index and returns the index | tuple. | | Returns | ------- | val : tuple of ints | Returns a tuple containing the indices of the current | iteration. | | ndincr(self) from numpy.lib._index_tricks_impl.ndindex | Increment the multi-dimensional index by one. | | This method is for backward compatibility only: do not use. | | .. deprecated:: 1.20.0 | This method has been advised against since numpy 1.8.0, but only | started emitting DeprecationWarning as of this version. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
numpy.nditer
Python Library Documentation: class nditer in module numpy
class nditer(builtins.object)
| nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K',
| casting='safe', op_axes=None, itershape=None, buffersize=0)
|
| Efficient multi-dimensional iterator object to iterate over arrays.
| To get started using this object, see the
| :ref:`introductory guide to array iteration <arrays.nditer>`.
|
| Parameters
| ----------
| op : ndarray or sequence of array_like
| The array(s) to iterate over.
|
| flags : sequence 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_flags : list 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_dtypes : dtype 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_axes : list 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`.
| itershape : tuple 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.
| buffersize : int, optional
| When buffering is enabled, controls the size of the temporary
| buffers. Set to 0 for the default value.
|
| Attributes
| ----------
| dtypes : tuple 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.
| finished : bool
| Whether the iteration over the operands is finished or not.
| has_delayed_bufalloc : bool
| If True, the iterator was created with the ``delay_bufalloc`` flag,
| and no reset() function was called on it yet.
| has_index : bool
| 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_index : bool
| 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.
| iterationneedsapi : bool
| Whether iteration requires access to the Python API, for example
| if one of the operands is an object array.
| iterindex : int
| An index which matches the order of iteration.
| itersize : int
| 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.
| ndim : int
| The dimensions of the iterator.
| nop : int
| The number of iterator operands.
| operands : tuple of operand(s)
| The array(s) to be iterated over. Valid only before the iterator is
| closed.
| shape : tuple 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.
|
| 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:
|
| >>> import numpy as np
|
| >>> 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 :meth:`~object.__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.
|
| Methods defined here:
|
| __copy__(...)
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __enter__(...)
|
| __exit__(...)
|
| __getitem__(self, key, /)
| Return self[key].
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __len__(self, /)
| Return len(self).
|
| __next__(self, /)
| Implement next(self).
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| close(...)
| close()
|
| Resolve all writeback semantics in writeable operands.
|
| .. versionadded:: 1.15.0
|
| See Also
| --------
|
| :ref:`nditer-context-manager`
|
| copy(...)
| copy()
|
| Get a copy of the iterator in its current state.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(10)
| >>> y = x + 1
| >>> it = np.nditer([x, y])
| >>> next(it)
| (array(0), array(1))
| >>> it2 = it.copy()
| >>> next(it2)
| (array(1), array(2))
|
| debug_print(...)
| debug_print()
|
| Print the current state of the `nditer` instance and debug info to stdout.
|
| enable_external_loop(...)
| 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(...)
| iternext()
|
| Check whether iterations are left, and perform a single internal iteration
| without returning the result. Used in the C-style pattern do-while
| pattern. For an example, see `nditer`.
|
| Returns
| -------
| iternext : bool
| Whether or not there are iterations left.
|
| remove_axis(...)
| remove_axis(i, /)
|
| Removes axis `i` from the iterator. Requires that the flag "multi_index"
| be enabled.
|
| remove_multi_index(...)
| remove_multi_index()
|
| When the "multi_index" flag was specified, this removes it, allowing
| the internal iteration structure to be optimized further.
|
| reset(...)
| reset()
|
| Reset the iterator to its initial state.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| dtypes
|
| finished
|
| has_delayed_bufalloc
|
| has_index
|
| has_multi_index
|
| index
|
| iterationneedsapi
|
| iterindex
|
| iterrange
|
| itersize
|
| itviews
|
| multi_index
|
| ndim
|
| nop
|
| operands
| operands[`Slice`]
|
| The array(s) to be iterated over. Valid only before the iterator is closed.
|
| shape
|
| value
numpy.negative
Python Library Documentation: ufunc
negative = <ufunc 'negative'>
negative(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Numerical negative, element-wise.
Parameters
----------
x : array_like or scalar
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
Returned array or scalar: `y = -x`.
This is a scalar if `x` is a scalar.
Examples
--------
>>> import numpy as np
>>> 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
Python Library Documentation: built-in function nested_iters in module numpy
nested_iters(...)
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
----------
op : ndarray or sequence of array_like
The array(s) to iterate over.
axes : list 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
-------
iters : tuple 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]
>>> import numpy as np
>>> 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
Python Library Documentation: NoneType object class NoneType(object) | Methods defined here: | | __bool__(self, /) | True if self else False | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature.
numpy.nextafter
Python Library Documentation: ufunc
nextafter = <ufunc 'nextafter'>
nextafter(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the next floating-point value after x1 towards x2, element-wise.
Parameters
----------
x1 : array_like
Values to find the next representable value of.
x2 : array_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).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
The next representable values of `x1` in the direction of `x2`.
This is a scalar if both `x1` and `x2` are scalars.
Examples
--------
>>> import numpy as np
>>> 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.nonzero
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
nonzero(a)
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:: 1.17.0
Use `atleast_1d` explicitly if this behavior is deliberate.
Parameters
----------
a : array_like
Input array.
Returns
-------
tuple_of_arrays : tuple
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
--------
>>> import numpy as np
>>> 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
Python Library Documentation: ufunc
not_equal = <ufunc 'not_equal'>
not_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return (x1 != x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
>>> import numpy as np
>>> 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])
numpy.number
Python Library Documentation: class number in module numpy class number(generic) | Abstract base class of all numeric scalar types. | | Method resolution order: | number | generic | builtins.object | | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Data and other attributes inherited from generic: | | __hash__ = None
numpy.object_
Python Library Documentation: class object_ in module numpy class object_(generic) | Any Python object. | | :Character code: ``'O'`` | | Method resolution order: | object_ | generic | builtins.object | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __call__(self, /, *args, **kwargs) | Call self as a function. | | __contains__(self, key, /) | Return bool(key in self). | | __delattr__(self, name, /) | Implement delattr(self, name). | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iadd__(self, value, /) | Implement self+=value. | | __imul__(self, value, /) | Implement self*=value. | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __release_buffer__(self, buffer, /) | Release the buffer object that exposes the underlying memory of the object. | | __rmul__(self, value, /) | Return value*self. | | __setattr__(self, name, value, /) | Implement setattr(self, name, value). | | __setitem__(self, key, value, /) | Set self[key] to value. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __mod__(self, value, /) | Return self%value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.ogrid
Python Library Documentation: OGridClass in module numpy.lib._index_tricks_impl object class OGridClass(nd_grid) | An instance which returns an open multi-dimensional "meshgrid". | | An instance 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 : ndarray or tuple of ndarrays | If the input is a single slice, returns an array. | If the input is multiple slices, returns a tuple of arrays, with | only one dimension not equal to 1. | | See Also | -------- | mgrid : like `ogrid` but returns dense (or fleshed out) mesh grids | meshgrid: return coordinate matrices from coordinate vectors | r_ : array concatenator | :ref:`how-to-partition` | | 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]])) | | Method resolution order: | OGridClass | nd_grid | builtins.object | | Methods defined here: | | __init__(self) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from nd_grid: | | __getitem__(self, key) | | ---------------------------------------------------------------------- | Data descriptors inherited from nd_grid: | | sparse
numpy.ones
Python Library Documentation: function ones in module numpy
ones(shape, dtype=None, order='C', *, device=None, like=None)
Return a new array of given shape and type, filled with ones.
Parameters
----------
shape : int or sequence of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
The desired data-type for the array, e.g., `numpy.int8`. Default is
`numpy.float64`.
order : {'C', 'F'}, optional, default: C
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
Array of ones with the given shape, dtype, and order.
See Also
--------
ones_like : Return an array of ones with shape and type of input.
empty : Return a new uninitialized array.
zeros : Return a new array setting values to zero.
full : Return a new array of given shape filled with value.
Examples
--------
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
ones_like(a, dtype=None, order='K', subok=True, shape=None, *, device=None)
Return an array of ones with the same shape and type as a given array.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of
the returned array.
dtype : data-type, optional
Overrides the data type of the result.
.. versionadded:: 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.
.. versionadded:: 1.6.0
subok : bool, 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.
shape : int 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.
.. versionadded:: 1.17.0
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
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
--------
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
outer(a, b, out=None)
Compute the outer product of two vectors.
Given two vectors `a` and `b` of length ``M`` and ``N``, respectively,
the outer product [1]_ is::
[[a_0*b_0 a_0*b_1 ... a_0*b_{N-1} ]
[a_1*b_0 .
[ ... .
[a_{M-1}*b_0 a_{M-1}*b_{N-1} ]]
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
.. versionadded:: 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.
linalg.outer : An Array API compatible variation of ``np.outer``,
which accepts 1-dimensional inputs only.
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:
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
packbits(...)
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
----------
a : array_like
An array of integers or booleans whose elements should be packed to
bits.
axis : int, 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'.
.. versionadded:: 1.17.0
Returns
-------
packed : ndarray
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
--------
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
pad(array, pad_width, mode='constant', **kwargs)
Pad an array.
Parameters
----------
array : array_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)`` or ``((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.
mode : str 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.
.. versionadded:: 1.17
<function>
Padding function, see Notes.
stat_length : sequence 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)`` or ``((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_values : sequence 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)`` or ``((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_values : sequence 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)`` or ``((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
-------
pad : ndarray
Padded array of rank equal to `array` with shape increased
according to `pad_width`.
Notes
-----
.. versionadded:: 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
vector : ndarray
A rank 1 array already padded with zeros. Padded values are
vector[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:].
iaxis_pad_width : tuple
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.
iaxis : int
The axis currently being calculated.
kwargs : dict
Any keyword arguments the function requires.
Examples
--------
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
partition(a, kth, axis=-1, kind='introselect', order=None)
Return a partitioned copy of an array.
Creates a copy of the array and partially sorts it 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. In the output array, all elements smaller than the k-th
element are located to the left of this element and all equal or greater
are located to its right. The ordering of the elements in the two
partitions on the either side of the k-th element in the output array is
undefined.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
Array to be sorted.
kth : int 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:: 1.22.0
Passing booleans as index is deprecated.
axis : int 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'.
order : str 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_array : ndarray
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.
The sort order of ``np.nan`` is bigger than ``np.inf``.
Examples
--------
>>> import numpy as np
>>> a = np.array([7, 1, 7, 7, 1, 5, 7, 2, 3, 2, 6, 2, 3, 0])
>>> p = np.partition(a, 4)
>>> p
array([0, 1, 2, 1, 2, 5, 2, 3, 3, 6, 7, 7, 7, 7]) # may vary
``p[4]`` is 2; all elements in ``p[:4]`` are less than or equal
to ``p[4]``, and all elements in ``p[5:]`` are greater than or
equal to ``p[4]``. The partition is::
[0, 1, 2, 1], [2], [5, 2, 3, 3, 6, 7, 7, 7, 7]
The next example shows the use of multiple values passed to `kth`.
>>> p2 = np.partition(a, (4, 8))
>>> p2
array([0, 1, 2, 1, 2, 3, 3, 2, 5, 6, 7, 7, 7, 7])
``p2[4]`` is 2 and ``p2[8]`` is 5. All elements in ``p2[:4]``
are less than or equal to ``p2[4]``, all elements in ``p2[5:8]``
are greater than or equal to ``p2[4]`` and less than or equal to
``p2[8]``, and all elements in ``p2[9:]`` are greater than or
equal to ``p2[8]``. The partition is::
[0, 1, 2, 1], [2], [3, 3, 2], [5], [6, 7, 7, 7, 7]
numpy.percentile
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
percentile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, weights=None, interpolation=None)
Compute the q-th percentile of the data along the specified axis.
Returns the q-th percentile(s) of the array elements.
Parameters
----------
a : array_like of real numbers
Input array or object that can be converted to an array.
q : array_like of float
Percentage or sequence of percentages for the percentiles to compute.
Values 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.
.. versionchanged:: 1.9.0
A tuple of axes is supported
out : ndarray, 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_input : bool, 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.
method : str, 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:
1. 'inverted_cdf'
2. 'averaged_inverted_cdf'
3. 'closest_observation'
4. 'interpolated_inverted_cdf'
5. 'hazen'
6. 'weibull'
7. 'linear' (default)
8. 'median_unbiased'
9. 'normal_unbiased'
The first three methods are discontinuous. NumPy further defines the
following discontinuous variations of the default 'linear' (7.) option:
* 'lower'
* 'higher',
* 'midpoint'
* 'nearest'
.. versionchanged:: 1.22.0
This argument was previously called "interpolation" and only
offered the "linear" default and last four options.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left in
the result as dimensions with size one. With this option, the
result will broadcast correctly against the original array `a`.
.. versionadded:: 1.9.0
weights : array_like, optional
An array of weights associated with the values in `a`. Each value in
`a` contributes to the percentile according to its associated weight.
The weights array can either be 1-D (in which case its length must be
the size of `a` along the given axis) or of the same shape as `a`.
If `weights=None`, then all data in `a` are assumed to have a
weight equal to one.
Only `method="inverted_cdf"` supports weights.
See the notes for more details.
.. versionadded:: 2.0.0
interpolation : str, optional
Deprecated name for the method keyword argument.
.. deprecated:: 1.22.0
Returns
-------
percentile : scalar 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
-----
The behavior of `numpy.percentile` with percentage `q` is
that of `numpy.quantile` with argument ``q/100``.
For more information, please see `numpy.quantile`.
Examples
--------
>>> import numpy as np
>>> 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:
.. plot::
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(bbox_to_anchor=(1.03, 1))
plt.tight_layout()
plt.show()
References
----------
.. [1] R. J. Hyndman and Y. Fan,
"Sample quantiles in statistical packages,"
The American Statistician, 50(4), pp. 361-365, 1996
numpy.permute_dims
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
transpose(a, axes=None)
Returns an array with axes transposed.
For a 1-D array, this returns an unchanged view of the original array, as a
transposed vector is simply the same vector.
To convert a 1-D array into a 2-D column vector, an additional dimension
must be added, e.g., ``np.atleast_2d(a).T`` achieves this, as does
``a[:, np.newaxis]``.
For a 2-D array, this is the standard matrix transpose.
For an n-D array, if axes are given, their order indicates how the
axes are permuted (see Examples). If axes are not provided, then
``transpose(a).shape == a.shape[::-1]``.
Parameters
----------
a : array_like
Input array.
axes : tuple or list of ints, optional
If specified, it must be a tuple or list which contains a permutation
of [0,1,...,N-1] where N is the number of axes of `a`. The `i`'th axis
of the returned array will correspond to the axis numbered ``axes[i]``
of the input. If not specified, defaults to ``range(a.ndim)[::-1]``,
which reverses the order of the axes.
Returns
-------
p : ndarray
`a` with its axes permuted. A view is returned whenever possible.
See Also
--------
ndarray.transpose : Equivalent method.
moveaxis : Move axes of an array to new positions.
argsort : Return the indices that would sort an array.
Notes
-----
Use ``transpose(a, argsort(axes))`` to invert the transposition of tensors
when using the `axes` keyword argument.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
[3, 4]])
>>> np.transpose(a)
array([[1, 3],
[2, 4]])
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> np.transpose(a)
array([1, 2, 3, 4])
>>> a = np.ones((1, 2, 3))
>>> np.transpose(a, (1, 0, 2)).shape
(2, 1, 3)
>>> a = np.ones((2, 3, 4, 5))
>>> np.transpose(a).shape
(5, 4, 3, 2)
numpy.pi
Python Library Documentation: float object
class float(object)
| float(x=0, /)
|
| Convert a string or number to a floating-point number, if possible.
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| True if self else False
|
| __ceil__(self, /)
| Return the ceiling as an Integral.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(self, /)
| Return the floor as an Integral.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Formats the float according to format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __int__(self, /)
| int(self)
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __round__(self, ndigits=None, /)
| Return the Integral closest to x, rounding half toward even.
|
| When an argument is passed, work like built-in round(x, ndigits).
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(self, /)
| Return the Integral closest to x between 0 and x.
|
| as_integer_ratio(self, /)
| Return a pair of integers, whose ratio is exactly equal to the original float.
|
| The ratio is in lowest terms and has a positive denominator. Raise
| OverflowError on infinities and a ValueError on NaNs.
|
| >>> (10.0).as_integer_ratio()
| (10, 1)
| >>> (0.0).as_integer_ratio()
| (0, 1)
| >>> (-.25).as_integer_ratio()
| (-1, 4)
|
| conjugate(self, /)
| Return self, the complex conjugate of any float.
|
| hex(self, /)
| Return a hexadecimal representation of a floating-point number.
|
| >>> (-0.1).hex()
| '-0x1.999999999999ap-4'
| >>> 3.14159.hex()
| '0x1.921f9f01b866ep+1'
|
| is_integer(self, /)
| Return True if the float is an integer.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __getformat__(typestr, /)
| You probably don't want to use this function.
|
| typestr
| Must be 'double' or 'float'.
|
| It exists mainly to be used in Python's test suite.
|
| This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE,
| little-endian' best describes the format of floating-point numbers used by the
| C type named by typestr.
|
| fromhex(string, /)
| Create a floating-point number from a hexadecimal string.
|
| >>> float.fromhex('0x1.ffffp10')
| 2047.984375
| >>> float.fromhex('-0x1p-1074')
| -5e-324
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| imag
| the imaginary part of a complex number
|
| real
| the real part of a complex number
numpy.piecewise
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
piecewise(x, condlist, funclist, *args, **kw)
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
----------
x : ndarray or scalar
The input domain.
condlist : list 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.
funclist : list 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.
args : tuple, 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')``.
kw : dict, 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
-------
out : ndarray
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
--------
>>> import numpy as np
Define the signum 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.place
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
place(arr, mask, vals)
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
----------
arr : ndarray
Array to put data into.
mask : array_like
Boolean mask array. Must have the same size as `a`.
vals : 1-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
--------
>>> import numpy as np
>>> arr = np.arange(6).reshape(2, 3)
>>> np.place(arr, arr>2, [44, 55])
>>> arr
array([[ 0, 1, 2],
[44, 55, 44]])
numpy.poly
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
poly(seq_of_zeros)
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
:doc:`transition guide </reference/routines.polynomials>`.
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_zeros : array_like, shape (N,) or (N, N)
A sequence of polynomial roots, or a square array or matrix object.
Returns
-------
c : ndarray
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, :math:`p_a(t)`, of an `n`-by-`n`
matrix **A** is given by
:math:`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 Trigonometry,
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:
>>> import numpy as np
>>> 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
Python Library Documentation: class poly1d in module numpy class poly1d(builtins.object) | poly1d(c_or_r, r=False, variable=None) | | 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 | :doc:`transition guide </reference/routines.polynomials>`. | | 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_r : array_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 | :math:`x^2 + 2x + 3`, whereas ``poly1d([1, 2, 3], True)`` returns | one that represents :math:`(x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x -6`. | r : bool, optional | If True, `c_or_r` specifies the polynomial's roots; the default | is False. | variable : str, optional | Changes the variable used when printing `p` from `x` to `variable` | (see Examples). | | Examples | -------- | Construct the polynomial :math:`x^2 + 2x + 3`: | | >>> import numpy as np | | >>> p = np.poly1d([1, 2, 3]) | >>> print(np.poly1d(p)) | 2 | 1 x + 2 x + 3 | | Evaluate the polynomial at :math:`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]) | | Methods defined here: | | __add__(self, other) from numpy.lib._polynomial_impl.poly1d | | __array__(self, t=None, copy=None) from numpy.lib._polynomial_impl.poly1d | | __call__(self, val) from numpy.lib._polynomial_impl.poly1d | Call self as a function. | | __div__(self, other) from numpy.lib._polynomial_impl.poly1d | | __eq__(self, other) from numpy.lib._polynomial_impl.poly1d | Return self==value. | | __getitem__(self, val) from numpy.lib._polynomial_impl.poly1d | | __init__(self, c_or_r, r=False, variable=None) from numpy.lib._polynomial_impl.poly1d | Initialize self. See help(type(self)) for accurate signature. | | __iter__(self) from numpy.lib._polynomial_impl.poly1d | | __len__(self) from numpy.lib._polynomial_impl.poly1d | | __mul__(self, other) from numpy.lib._polynomial_impl.poly1d | | __ne__(self, other) from numpy.lib._polynomial_impl.poly1d | Return self!=value. | | __neg__(self) from numpy.lib._polynomial_impl.poly1d | | __pos__(self) from numpy.lib._polynomial_impl.poly1d | | __pow__(self, val) from numpy.lib._polynomial_impl.poly1d | | __radd__(self, other) from numpy.lib._polynomial_impl.poly1d | | __rdiv__(self, other) from numpy.lib._polynomial_impl.poly1d | | __repr__(self) from numpy.lib._polynomial_impl.poly1d | Return repr(self). | | __rmul__(self, other) from numpy.lib._polynomial_impl.poly1d | | __rsub__(self, other) from numpy.lib._polynomial_impl.poly1d | | __rtruediv__ = __rdiv__(self, other) | | __setitem__(self, key, val) from numpy.lib._polynomial_impl.poly1d | | __str__(self) from numpy.lib._polynomial_impl.poly1d | Return str(self). | | __sub__(self, other) from numpy.lib._polynomial_impl.poly1d | | __truediv__ = __div__(self, other) | | deriv(self, m=1) from numpy.lib._polynomial_impl.poly1d | Return a derivative of this polynomial. | | Refer to `polyder` for full documentation. | | See Also | -------- | polyder : equivalent function | | integ(self, m=1, k=0) from numpy.lib._polynomial_impl.poly1d | Return an antiderivative (indefinite integral) of this polynomial. | | Refer to `polyint` for full documentation. | | See Also | -------- | polyint : equivalent function | | ---------------------------------------------------------------------- | Readonly properties defined here: | | 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 | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | c | The polynomial coefficients | | coef | The polynomial coefficients | | coefficients | The polynomial coefficients | | coeffs | The polynomial coefficients | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
numpy.polyadd
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
polyadd(a1, a2)
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
:doc:`transition guide </reference/routines.polynomials>`.
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, a2 : array_like or poly1d object
Input polynomials.
Returns
-------
out : ndarray 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
--------
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
polyder(p, m=1)
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
:doc:`transition guide </reference/routines.polynomials>`.
Parameters
----------
p : poly1d or sequence
Polynomial to differentiate.
A sequence is interpreted as polynomial coefficients, see `poly1d`.
m : int, optional
Order of differentiation (default: 1)
Returns
-------
der : poly1d
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 :math:`x^3 + x^2 + x^1 + 1` is:
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
polydiv(u, v)
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
:doc:`transition guide </reference/routines.polynomials>`.
The input arrays are the coefficients (including any coefficients
equal to zero) of the "numerator" (dividend) and "denominator"
(divisor) polynomials, respectively.
Parameters
----------
u : array_like or poly1d
Dividend polynomial's coefficients.
v : array_like or poly1d
Divisor polynomial's coefficients.
Returns
-------
q : ndarray
Coefficients, including those equal to zero, of the quotient.
r : ndarray
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
--------
.. math:: \frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)
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
:doc:`transition guide </reference/routines.polynomials>`.
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 <numpy.polynomial.polynomial.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
----------
x : array_like, shape (M,)
x-coordinates of the M sample points ``(x[i], y[i])``.
y : array_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.
deg : int
Degree of the fitting polynomial
rcond : float, 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.
full : bool, 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.
w : array_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.
cov : bool 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
-------
p : ndarray, 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`.
V : ndarray, shape (deg + 1, deg + 1) or (deg + 1, deg + 1, 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.exceptions.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
.. math::
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 `~exceptions.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 numpy as np
>>> 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.exceptions.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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
polyint(p, m=1, k=None)
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
:doc:`transition guide </reference/routines.polynomials>`.
The returned order `m` antiderivative `P` of polynomial `p` satisfies
:math:`\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
.. math:: \frac{k_{m-1}}{0!} x^0 + \ldots + \frac{k_0}{(m-1)!}x^{m-1}
of `P` so that :math:`P^{(j)}(0) = k_{m-j-1}`.
Parameters
----------
p : array_like or poly1d
Polynomial to integrate.
A sequence is interpreted as polynomial coefficients, see `poly1d`.
m : int, optional
Order of the antiderivative. (Default: 1)
k : list 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:
>>> import numpy as np
>>> 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
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
polymul(a1, a2)
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
:doc:`transition guide </reference/routines.polynomials>`.
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, a2 : array_like or poly1d object
Input polynomials.
Returns
-------
out : ndarray 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
--------
>>> import numpy as np
>>> 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
Python Library Documentation: package numpy.polynomial in numpy
NAME
numpy.polynomial - A sub-package for efficiently dealing with polynomials.
DESCRIPTION
Within the documentation for this sub-package, a "finite power series,"
i.e., a polynomial (also referred to simply as a "series") is represented
by a 1-D numpy array of the polynomial's coefficients, ordered from lowest
order term to highest. For example, array([1,2,3]) represents
``P_0 + 2*P_1 + 3*P_2``, where P_n is the n-th order basis polynomial
applicable to the specific module in question, e.g., `polynomial` (which
"wraps" the "standard" basis) or `chebyshev`. For optimal performance,
all operations on polynomials, including evaluation at an argument, are
implemented as operations on the coefficients. Additional (module-specific)
information can be found in the docstring for the module of interest.
This package provides *convenience classes* for each of six different kinds
of polynomials:
======================== ================
**Name** **Provides**
======================== ================
`~polynomial.Polynomial` Power series
`~chebyshev.Chebyshev` Chebyshev series
`~legendre.Legendre` Legendre series
`~laguerre.Laguerre` Laguerre series
`~hermite.Hermite` Hermite series
`~hermite_e.HermiteE` HermiteE series
======================== ================
These *convenience classes* provide a consistent interface for creating,
manipulating, and fitting data with polynomials of different bases.
The convenience classes are the preferred interface for the `~numpy.polynomial`
package, and are available from the ``numpy.polynomial`` namespace.
This eliminates the need to navigate to the corresponding submodules, e.g.
``np.polynomial.Polynomial`` or ``np.polynomial.Chebyshev`` instead of
``np.polynomial.polynomial.Polynomial`` or
``np.polynomial.chebyshev.Chebyshev``, respectively.
The classes provide a more consistent and concise interface than the
type-specific functions defined in the submodules for each type of polynomial.
For example, to fit a Chebyshev polynomial with degree ``1`` to data given
by arrays ``xdata`` and ``ydata``, the
`~chebyshev.Chebyshev.fit` class method::
>>> from numpy.polynomial import Chebyshev
>>> xdata = [1, 2, 3, 4]
>>> ydata = [1, 4, 9, 16]
>>> c = Chebyshev.fit(xdata, ydata, deg=1)
is preferred over the `chebyshev.chebfit` function from the
``np.polynomial.chebyshev`` module::
>>> from numpy.polynomial.chebyshev import chebfit
>>> c = chebfit(xdata, ydata, deg=1)
See :doc:`routines.polynomials.classes` for more details.
Convenience Classes
===================
The following lists the various constants and methods common to all of
the classes representing the various kinds of polynomials. In the following,
the term ``Poly`` represents any one of the convenience classes (e.g.
`~polynomial.Polynomial`, `~chebyshev.Chebyshev`, `~hermite.Hermite`, etc.)
while the lowercase ``p`` represents an **instance** of a polynomial class.
Constants
---------
- ``Poly.domain`` -- Default domain
- ``Poly.window`` -- Default window
- ``Poly.basis_name`` -- String used to represent the basis
- ``Poly.maxpower`` -- Maximum value ``n`` such that ``p**n`` is allowed
- ``Poly.nickname`` -- String used in printing
Creation
--------
Methods for creating polynomial instances.
- ``Poly.basis(degree)`` -- Basis polynomial of given degree
- ``Poly.identity()`` -- ``p`` where ``p(x) = x`` for all ``x``
- ``Poly.fit(x, y, deg)`` -- ``p`` of degree ``deg`` with coefficients
determined by the least-squares fit to the data ``x``, ``y``
- ``Poly.fromroots(roots)`` -- ``p`` with specified roots
- ``p.copy()`` -- Create a copy of ``p``
Conversion
----------
Methods for converting a polynomial instance of one kind to another.
- ``p.cast(Poly)`` -- Convert ``p`` to instance of kind ``Poly``
- ``p.convert(Poly)`` -- Convert ``p`` to instance of kind ``Poly`` or map
between ``domain`` and ``window``
Calculus
--------
- ``p.deriv()`` -- Take the derivative of ``p``
- ``p.integ()`` -- Integrate ``p``
Validation
----------
- ``Poly.has_samecoef(p1, p2)`` -- Check if coefficients match
- ``Poly.has_samedomain(p1, p2)`` -- Check if domains match
- ``Poly.has_sametype(p1, p2)`` -- Check if types match
- ``Poly.has_samewindow(p1, p2)`` -- Check if windows match
Misc
----
- ``p.linspace()`` -- Return ``x, p(x)`` at equally-spaced points in ``domain``
- ``p.mapparms()`` -- Return the parameters for the linear mapping between
``domain`` and ``window``.
- ``p.roots()`` -- Return the roots of ``p``.
- ``p.trim()`` -- Remove trailing coefficients.
- ``p.cutdeg(degree)`` -- Truncate ``p`` to given degree
- ``p.truncate(size)`` -- Truncate ``p`` to given size
PACKAGE CONTENTS
_polybase
chebyshev
hermite
hermite_e
laguerre
legendre
polynomial
polyutils
tests (package)
CLASSES
numpy.polynomial._polybase.ABCPolyBase(abc.ABC)
numpy.polynomial.chebyshev.Chebyshev
numpy.polynomial.hermite.Hermite
numpy.polynomial.hermite_e.HermiteE
numpy.polynomial.laguerre.Laguerre
numpy.polynomial.legendre.Legendre
numpy.polynomial.polynomial.Polynomial
class Chebyshev(numpy.polynomial._polybase.ABCPolyBase)
| Chebyshev(coef, domain=None, window=None, symbol='x')
|
| A Chebyshev series class.
|
| The Chebyshev class provides the standard Python numerical methods
| '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
| attributes and methods listed below.
|
| Parameters
| ----------
| coef : array_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.].
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol used to represent the independent variable in string
| representations of the polynomial expression, e.g. for printing.
| The symbol must be a valid Python identifier. Default value is 'x'.
|
| .. versionadded:: 1.24
|
| Method resolution order:
| Chebyshev
| numpy.polynomial._polybase.ABCPolyBase
| abc.ABC
| builtins.object
|
| Class methods defined here:
|
| interpolate(func, deg, domain=None, args=())
| Interpolate a function at the Chebyshev points of the first kind.
|
| Returns the series that interpolates `func` at the Chebyshev points of
| the first kind scaled and shifted to the `domain`. The resulting series
| tends to a minmax approximation of `func` when the function is
| continuous in the domain.
|
| .. versionadded:: 1.14.0
|
| Parameters
| ----------
| func : function
| The function to be interpolated. It must be a function of a single
| variable of the form ``f(x, a, b, c...)``, where ``a, b, c...`` are
| extra arguments passed in the `args` parameter.
| deg : int
| Degree of the interpolating polynomial.
| domain : {None, [beg, end]}, optional
| Domain over which `func` is interpolated. The default is None, in
| which case the domain is [-1, 1].
| args : tuple, optional
| Extra arguments to be used in the function call. Default is no
| extra arguments.
|
| Returns
| -------
| polynomial : Chebyshev instance
| Interpolating Chebyshev instance.
|
| Notes
| -----
| See `numpy.polynomial.chebinterpolate` for more details.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| basis_name = 'T'
|
| domain = array([-1., 1.])
|
| window = array([-1., 1.])
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __add__(self, other)
|
| __call__(self, arg)
| Call self as a function.
|
| __divmod__(self, other)
|
| __eq__(self, other)
| Return self==value.
|
| __floordiv__(self, other)
|
| __format__(self, fmt_str)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, coef, domain=None, window=None, symbol='x')
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self)
|
| __len__(self)
|
| __mod__(self, other)
|
| __mul__(self, other)
|
| __ne__(self, other)
| Return self!=value.
|
| __neg__(self)
|
| __pos__(self)
|
| __pow__(self, other)
|
| __radd__(self, other)
|
| __rdiv__(self, other)
|
| __rdivmod__(self, other)
|
| __repr__(self)
| Return repr(self).
|
| __rfloordiv__(self, other)
|
| __rmod__(self, other)
|
| __rmul__(self, other)
|
| __rsub__(self, other)
|
| __rtruediv__(self, other)
|
| __setstate__(self, dict)
|
| __str__(self)
| Return str(self).
|
| __sub__(self, other)
|
| __truediv__(self, other)
|
| convert(self, domain=None, kind=None, window=None)
| Convert series to a different kind and/or domain and/or window.
|
| Parameters
| ----------
| domain : array_like, optional
| The domain of the converted series. If the value is None,
| the default domain of `kind` is used.
| kind : class, optional
| The polynomial series type class to which the current instance
| should be converted. If kind is None, then the class of the
| current instance is used.
| window : array_like, optional
| The window of the converted series. If the value is None,
| the default window of `kind` is used.
|
| Returns
| -------
| new_series : series
| The returned class can be of different type than the current
| instance and/or have a different domain and/or different
| window.
|
| Notes
| -----
| Conversion between domains and class types can result in
| numerically ill defined series.
|
| copy(self)
| Return a copy.
|
| Returns
| -------
| new_series : series
| Copy of self.
|
| cutdeg(self, deg)
| Truncate series to the given degree.
|
| Reduce the degree of the series to `deg` by discarding the
| high order terms. If `deg` is greater than the current degree a
| copy of the current series is returned. This can be useful in least
| squares where the coefficients of the high degree terms may be very
| small.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| deg : non-negative int
| The series is reduced to degree `deg` by discarding the high
| order terms. The value of `deg` must be a non-negative integer.
|
| Returns
| -------
| new_series : series
| New instance of series with reduced degree.
|
| degree(self)
| The degree of the series.
|
| .. versionadded:: 1.5.0
|
| Returns
| -------
| degree : int
| Degree of the series, one less than the number of coefficients.
|
| Examples
| --------
|
| Create a polynomial object for ``1 + 7*x + 4*x**2``:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 4])
| >>> print(poly)
| 1.0 + 7.0·x + 4.0·x²
| >>> poly.degree()
| 2
|
| Note that this method does not check for non-zero coefficients.
| You must trim the polynomial to remove any trailing zeroes:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 0])
| >>> print(poly)
| 1.0 + 7.0·x + 0.0·x²
| >>> poly.degree()
| 2
| >>> poly.trim().degree()
| 1
|
| deriv(self, m=1)
| Differentiate.
|
| Return a series instance of that is the derivative of the current
| series.
|
| Parameters
| ----------
| m : non-negative int
| Find the derivative of order `m`.
|
| Returns
| -------
| new_series : series
| A new series representing the derivative. The domain is the same
| as the domain of the differentiated series.
|
| has_samecoef(self, other)
| Check if coefficients match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``coef`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the coefficients are the same, False otherwise.
|
| has_samedomain(self, other)
| Check if domains match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``domain`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the domains are the same, False otherwise.
|
| has_sametype(self, other)
| Check if types match.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| other : object
| Class instance.
|
| Returns
| -------
| bool : boolean
| True if other is same class as self
|
| has_samewindow(self, other)
| Check if windows match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``window`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the windows are the same, False otherwise.
|
| integ(self, m=1, k=[], lbnd=None)
| Integrate.
|
| Return a series instance that is the definite integral of the
| current series.
|
| Parameters
| ----------
| m : non-negative int
| The number of integrations to perform.
| k : array_like
| Integration constants. The first constant is applied to the
| first integration, the second to the second, and so on. The
| list of values must less than or equal to `m` in length and any
| missing values are set to zero.
| lbnd : Scalar
| The lower bound of the definite integral.
|
| Returns
| -------
| new_series : series
| A new series representing the integral. The domain is the same
| as the domain of the integrated series.
|
| linspace(self, n=100, domain=None)
| Return x, y values at equally spaced points in domain.
|
| Returns the x, y values at `n` linearly spaced points across the
| domain. Here y is the value of the polynomial at the points x. By
| default the domain is the same as that of the series instance.
| This method is intended mostly as a plotting aid.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| n : int, optional
| Number of point pairs to return. The default value is 100.
| domain : {None, array_like}, optional
| If not None, the specified domain is used instead of that of
| the calling instance. It should be of the form ``[beg,end]``.
| The default is None which case the class domain is used.
|
| Returns
| -------
| x, y : ndarray
| x is equal to linspace(self.domain[0], self.domain[1], n) and
| y is the series evaluated at element of x.
|
| mapparms(self)
| Return the mapping parameters.
|
| The returned values define a linear map ``off + scl*x`` that is
| applied to the input arguments before the series is evaluated. The
| map depends on the ``domain`` and ``window``; if the current
| ``domain`` is equal to the ``window`` the resulting map is the
| identity. If the coefficients of the series instance are to be
| used by themselves outside this class, then the linear function
| must be substituted for the ``x`` in the standard representation of
| the base polynomials.
|
| Returns
| -------
| off, scl : float or complex
| The mapping function is defined by ``off + scl*x``.
|
| Notes
| -----
| If the current domain is the interval ``[l1, r1]`` and the window
| is ``[l2, r2]``, then the linear mapping function ``L`` is
| defined by the equations::
|
| L(l1) = l2
| L(r1) = r2
|
| roots(self)
| Return the roots of the series polynomial.
|
| Compute the roots for the series. Note that the accuracy of the
| roots decreases the further outside the `domain` they lie.
|
| Returns
| -------
| roots : ndarray
| Array containing the roots of the series.
|
| trim(self, tol=0)
| Remove trailing coefficients
|
| Remove trailing coefficients until a coefficient is reached whose
| absolute value greater than `tol` or the beginning of the series is
| reached. If all the coefficients would be removed the series is set
| to ``[0]``. A new series instance is returned with the new
| coefficients. The current instance remains unchanged.
|
| Parameters
| ----------
| tol : non-negative number.
| All trailing coefficients less than `tol` will be removed.
|
| Returns
| -------
| new_series : series
| New instance of series with trimmed coefficients.
|
| truncate(self, size)
| Truncate series to length `size`.
|
| Reduce the series to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer. This
| can be useful in least squares where the coefficients of the
| high degree terms may be very small.
|
| Parameters
| ----------
| size : positive int
| The series is reduced to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer.
|
| Returns
| -------
| new_series : series
| New instance of series with truncated coefficients.
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| basis(deg, domain=None, window=None, symbol='x')
| Series basis polynomial of degree `deg`.
|
| Returns the series representing the basis polynomial of degree `deg`.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| deg : int
| Degree of the basis polynomial for the series. Must be >= 0.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series with the coefficient of the `deg` term set to one and
| all others zero.
|
| cast(series, domain=None, window=None)
| Convert series to series of this class.
|
| The `series` is expected to be an instance of some polynomial
| series of one of the types supported by by the numpy.polynomial
| module, but could be some other class that supports the convert
| method.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| series : series
| The series instance to be converted.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
|
| Returns
| -------
| new_series : series
| A series of the same kind as the calling class and equal to
| `series` when evaluated.
|
| See Also
| --------
| convert : similar instance method
|
| fit(x, y, deg, domain=None, rcond=None, full=False, w=None, window=None, symbol='x')
| Least squares fit to data.
|
| Return a series instance that is the least squares fit to the data
| `y` sampled at `x`. The domain of the returned instance can be
| specified and this will often result in a superior fit with less
| chance of ill conditioning.
|
| Parameters
| ----------
| x : array_like, shape (M,)
| x-coordinates of the M sample points ``(x[i], y[i])``.
| y : array_like, shape (M,)
| y-coordinates of the M sample points ``(x[i], y[i])``.
| deg : int or 1-D array_like
| Degree(s) of the fitting polynomials. If `deg` is a single integer
| all terms up to and including the `deg`'th term are included in the
| fit. For NumPy versions >= 1.11.0 a list of integers specifying the
| degrees of the terms to include may be used instead.
| domain : {None, [beg, end], []}, optional
| Domain to use for the returned series. If ``None``,
| then a minimal domain that covers the points `x` is chosen. If
| ``[]`` the class domain is used. The default value was the
| class domain in NumPy 1.4 and ``None`` in later versions.
| The ``[]`` option was added in numpy 1.5.0.
| rcond : float, 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.
| full : bool, 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.
| w : array_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.
|
| .. versionadded:: 1.5.0
| window : {[beg, end]}, optional
| Window to use for the returned series. The default
| value is the default class domain
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series that represents the least squares fit to the data and
| has the domain and window specified in the call. If the
| coefficients for the unscaled and unshifted basis polynomials are
| of interest, do ``new_series.convert().coef``.
|
| [resid, rank, sv, rcond] : list
| These values are only returned if ``full == True``
|
| - resid -- sum of squared residuals of the least squares fit
| - rank -- the numerical rank of the scaled Vandermonde matrix
| - sv -- singular values of the scaled Vandermonde matrix
| - rcond -- value of `rcond`.
|
| For more details, see `linalg.lstsq`.
|
| fromroots(roots, domain=[], window=None, symbol='x')
| Return series instance that has the specified roots.
|
| Returns a series representing the product
| ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
| list of roots.
|
| Parameters
| ----------
| roots : array_like
| List of roots.
| domain : {[], None, array_like}, optional
| Domain for the resulting series. If None the domain is the
| interval from the smallest root to the largest. If [] the
| domain is the class domain. The default is [].
| window : {None, array_like}, optional
| Window for the returned series. If None the class window is
| used. The default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series with the specified roots.
|
| identity(domain=None, window=None, symbol='x')
| Identity function.
|
| If ``p`` is the returned series, then ``p(x) == x`` for all
| values of x.
|
| Parameters
| ----------
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series of representing the identity.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| symbol
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __array_ufunc__ = None
|
| __hash__ = None
|
| maxpower = 100
class Hermite(numpy.polynomial._polybase.ABCPolyBase)
| Hermite(coef, domain=None, window=None, symbol='x')
|
| An Hermite series class.
|
| The Hermite class provides the standard Python numerical methods
| '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
| attributes and methods listed below.
|
| Parameters
| ----------
| coef : array_like
| Hermite coefficients in order of increasing degree, i.e,
| ``(1, 2, 3)`` gives ``1*H_0(x) + 2*H_1(x) + 3*H_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.].
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol used to represent the independent variable in string
| representations of the polynomial expression, e.g. for printing.
| The symbol must be a valid Python identifier. Default value is 'x'.
|
| .. versionadded:: 1.24
|
| Method resolution order:
| Hermite
| numpy.polynomial._polybase.ABCPolyBase
| abc.ABC
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| basis_name = 'H'
|
| domain = array([-1., 1.])
|
| window = array([-1., 1.])
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __add__(self, other)
|
| __call__(self, arg)
| Call self as a function.
|
| __divmod__(self, other)
|
| __eq__(self, other)
| Return self==value.
|
| __floordiv__(self, other)
|
| __format__(self, fmt_str)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, coef, domain=None, window=None, symbol='x')
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self)
|
| __len__(self)
|
| __mod__(self, other)
|
| __mul__(self, other)
|
| __ne__(self, other)
| Return self!=value.
|
| __neg__(self)
|
| __pos__(self)
|
| __pow__(self, other)
|
| __radd__(self, other)
|
| __rdiv__(self, other)
|
| __rdivmod__(self, other)
|
| __repr__(self)
| Return repr(self).
|
| __rfloordiv__(self, other)
|
| __rmod__(self, other)
|
| __rmul__(self, other)
|
| __rsub__(self, other)
|
| __rtruediv__(self, other)
|
| __setstate__(self, dict)
|
| __str__(self)
| Return str(self).
|
| __sub__(self, other)
|
| __truediv__(self, other)
|
| convert(self, domain=None, kind=None, window=None)
| Convert series to a different kind and/or domain and/or window.
|
| Parameters
| ----------
| domain : array_like, optional
| The domain of the converted series. If the value is None,
| the default domain of `kind` is used.
| kind : class, optional
| The polynomial series type class to which the current instance
| should be converted. If kind is None, then the class of the
| current instance is used.
| window : array_like, optional
| The window of the converted series. If the value is None,
| the default window of `kind` is used.
|
| Returns
| -------
| new_series : series
| The returned class can be of different type than the current
| instance and/or have a different domain and/or different
| window.
|
| Notes
| -----
| Conversion between domains and class types can result in
| numerically ill defined series.
|
| copy(self)
| Return a copy.
|
| Returns
| -------
| new_series : series
| Copy of self.
|
| cutdeg(self, deg)
| Truncate series to the given degree.
|
| Reduce the degree of the series to `deg` by discarding the
| high order terms. If `deg` is greater than the current degree a
| copy of the current series is returned. This can be useful in least
| squares where the coefficients of the high degree terms may be very
| small.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| deg : non-negative int
| The series is reduced to degree `deg` by discarding the high
| order terms. The value of `deg` must be a non-negative integer.
|
| Returns
| -------
| new_series : series
| New instance of series with reduced degree.
|
| degree(self)
| The degree of the series.
|
| .. versionadded:: 1.5.0
|
| Returns
| -------
| degree : int
| Degree of the series, one less than the number of coefficients.
|
| Examples
| --------
|
| Create a polynomial object for ``1 + 7*x + 4*x**2``:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 4])
| >>> print(poly)
| 1.0 + 7.0·x + 4.0·x²
| >>> poly.degree()
| 2
|
| Note that this method does not check for non-zero coefficients.
| You must trim the polynomial to remove any trailing zeroes:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 0])
| >>> print(poly)
| 1.0 + 7.0·x + 0.0·x²
| >>> poly.degree()
| 2
| >>> poly.trim().degree()
| 1
|
| deriv(self, m=1)
| Differentiate.
|
| Return a series instance of that is the derivative of the current
| series.
|
| Parameters
| ----------
| m : non-negative int
| Find the derivative of order `m`.
|
| Returns
| -------
| new_series : series
| A new series representing the derivative. The domain is the same
| as the domain of the differentiated series.
|
| has_samecoef(self, other)
| Check if coefficients match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``coef`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the coefficients are the same, False otherwise.
|
| has_samedomain(self, other)
| Check if domains match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``domain`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the domains are the same, False otherwise.
|
| has_sametype(self, other)
| Check if types match.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| other : object
| Class instance.
|
| Returns
| -------
| bool : boolean
| True if other is same class as self
|
| has_samewindow(self, other)
| Check if windows match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``window`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the windows are the same, False otherwise.
|
| integ(self, m=1, k=[], lbnd=None)
| Integrate.
|
| Return a series instance that is the definite integral of the
| current series.
|
| Parameters
| ----------
| m : non-negative int
| The number of integrations to perform.
| k : array_like
| Integration constants. The first constant is applied to the
| first integration, the second to the second, and so on. The
| list of values must less than or equal to `m` in length and any
| missing values are set to zero.
| lbnd : Scalar
| The lower bound of the definite integral.
|
| Returns
| -------
| new_series : series
| A new series representing the integral. The domain is the same
| as the domain of the integrated series.
|
| linspace(self, n=100, domain=None)
| Return x, y values at equally spaced points in domain.
|
| Returns the x, y values at `n` linearly spaced points across the
| domain. Here y is the value of the polynomial at the points x. By
| default the domain is the same as that of the series instance.
| This method is intended mostly as a plotting aid.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| n : int, optional
| Number of point pairs to return. The default value is 100.
| domain : {None, array_like}, optional
| If not None, the specified domain is used instead of that of
| the calling instance. It should be of the form ``[beg,end]``.
| The default is None which case the class domain is used.
|
| Returns
| -------
| x, y : ndarray
| x is equal to linspace(self.domain[0], self.domain[1], n) and
| y is the series evaluated at element of x.
|
| mapparms(self)
| Return the mapping parameters.
|
| The returned values define a linear map ``off + scl*x`` that is
| applied to the input arguments before the series is evaluated. The
| map depends on the ``domain`` and ``window``; if the current
| ``domain`` is equal to the ``window`` the resulting map is the
| identity. If the coefficients of the series instance are to be
| used by themselves outside this class, then the linear function
| must be substituted for the ``x`` in the standard representation of
| the base polynomials.
|
| Returns
| -------
| off, scl : float or complex
| The mapping function is defined by ``off + scl*x``.
|
| Notes
| -----
| If the current domain is the interval ``[l1, r1]`` and the window
| is ``[l2, r2]``, then the linear mapping function ``L`` is
| defined by the equations::
|
| L(l1) = l2
| L(r1) = r2
|
| roots(self)
| Return the roots of the series polynomial.
|
| Compute the roots for the series. Note that the accuracy of the
| roots decreases the further outside the `domain` they lie.
|
| Returns
| -------
| roots : ndarray
| Array containing the roots of the series.
|
| trim(self, tol=0)
| Remove trailing coefficients
|
| Remove trailing coefficients until a coefficient is reached whose
| absolute value greater than `tol` or the beginning of the series is
| reached. If all the coefficients would be removed the series is set
| to ``[0]``. A new series instance is returned with the new
| coefficients. The current instance remains unchanged.
|
| Parameters
| ----------
| tol : non-negative number.
| All trailing coefficients less than `tol` will be removed.
|
| Returns
| -------
| new_series : series
| New instance of series with trimmed coefficients.
|
| truncate(self, size)
| Truncate series to length `size`.
|
| Reduce the series to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer. This
| can be useful in least squares where the coefficients of the
| high degree terms may be very small.
|
| Parameters
| ----------
| size : positive int
| The series is reduced to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer.
|
| Returns
| -------
| new_series : series
| New instance of series with truncated coefficients.
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| basis(deg, domain=None, window=None, symbol='x')
| Series basis polynomial of degree `deg`.
|
| Returns the series representing the basis polynomial of degree `deg`.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| deg : int
| Degree of the basis polynomial for the series. Must be >= 0.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series with the coefficient of the `deg` term set to one and
| all others zero.
|
| cast(series, domain=None, window=None)
| Convert series to series of this class.
|
| The `series` is expected to be an instance of some polynomial
| series of one of the types supported by by the numpy.polynomial
| module, but could be some other class that supports the convert
| method.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| series : series
| The series instance to be converted.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
|
| Returns
| -------
| new_series : series
| A series of the same kind as the calling class and equal to
| `series` when evaluated.
|
| See Also
| --------
| convert : similar instance method
|
| fit(x, y, deg, domain=None, rcond=None, full=False, w=None, window=None, symbol='x')
| Least squares fit to data.
|
| Return a series instance that is the least squares fit to the data
| `y` sampled at `x`. The domain of the returned instance can be
| specified and this will often result in a superior fit with less
| chance of ill conditioning.
|
| Parameters
| ----------
| x : array_like, shape (M,)
| x-coordinates of the M sample points ``(x[i], y[i])``.
| y : array_like, shape (M,)
| y-coordinates of the M sample points ``(x[i], y[i])``.
| deg : int or 1-D array_like
| Degree(s) of the fitting polynomials. If `deg` is a single integer
| all terms up to and including the `deg`'th term are included in the
| fit. For NumPy versions >= 1.11.0 a list of integers specifying the
| degrees of the terms to include may be used instead.
| domain : {None, [beg, end], []}, optional
| Domain to use for the returned series. If ``None``,
| then a minimal domain that covers the points `x` is chosen. If
| ``[]`` the class domain is used. The default value was the
| class domain in NumPy 1.4 and ``None`` in later versions.
| The ``[]`` option was added in numpy 1.5.0.
| rcond : float, 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.
| full : bool, 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.
| w : array_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.
|
| .. versionadded:: 1.5.0
| window : {[beg, end]}, optional
| Window to use for the returned series. The default
| value is the default class domain
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series that represents the least squares fit to the data and
| has the domain and window specified in the call. If the
| coefficients for the unscaled and unshifted basis polynomials are
| of interest, do ``new_series.convert().coef``.
|
| [resid, rank, sv, rcond] : list
| These values are only returned if ``full == True``
|
| - resid -- sum of squared residuals of the least squares fit
| - rank -- the numerical rank of the scaled Vandermonde matrix
| - sv -- singular values of the scaled Vandermonde matrix
| - rcond -- value of `rcond`.
|
| For more details, see `linalg.lstsq`.
|
| fromroots(roots, domain=[], window=None, symbol='x')
| Return series instance that has the specified roots.
|
| Returns a series representing the product
| ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
| list of roots.
|
| Parameters
| ----------
| roots : array_like
| List of roots.
| domain : {[], None, array_like}, optional
| Domain for the resulting series. If None the domain is the
| interval from the smallest root to the largest. If [] the
| domain is the class domain. The default is [].
| window : {None, array_like}, optional
| Window for the returned series. If None the class window is
| used. The default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series with the specified roots.
|
| identity(domain=None, window=None, symbol='x')
| Identity function.
|
| If ``p`` is the returned series, then ``p(x) == x`` for all
| values of x.
|
| Parameters
| ----------
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series of representing the identity.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| symbol
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __array_ufunc__ = None
|
| __hash__ = None
|
| maxpower = 100
class HermiteE(numpy.polynomial._polybase.ABCPolyBase)
| HermiteE(coef, domain=None, window=None, symbol='x')
|
| An HermiteE series class.
|
| The HermiteE class provides the standard Python numerical methods
| '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
| attributes and methods listed below.
|
| Parameters
| ----------
| coef : array_like
| HermiteE coefficients in order of increasing degree, i.e,
| ``(1, 2, 3)`` gives ``1*He_0(x) + 2*He_1(X) + 3*He_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.].
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol used to represent the independent variable in string
| representations of the polynomial expression, e.g. for printing.
| The symbol must be a valid Python identifier. Default value is 'x'.
|
| .. versionadded:: 1.24
|
| Method resolution order:
| HermiteE
| numpy.polynomial._polybase.ABCPolyBase
| abc.ABC
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| basis_name = 'He'
|
| domain = array([-1., 1.])
|
| window = array([-1., 1.])
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __add__(self, other)
|
| __call__(self, arg)
| Call self as a function.
|
| __divmod__(self, other)
|
| __eq__(self, other)
| Return self==value.
|
| __floordiv__(self, other)
|
| __format__(self, fmt_str)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, coef, domain=None, window=None, symbol='x')
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self)
|
| __len__(self)
|
| __mod__(self, other)
|
| __mul__(self, other)
|
| __ne__(self, other)
| Return self!=value.
|
| __neg__(self)
|
| __pos__(self)
|
| __pow__(self, other)
|
| __radd__(self, other)
|
| __rdiv__(self, other)
|
| __rdivmod__(self, other)
|
| __repr__(self)
| Return repr(self).
|
| __rfloordiv__(self, other)
|
| __rmod__(self, other)
|
| __rmul__(self, other)
|
| __rsub__(self, other)
|
| __rtruediv__(self, other)
|
| __setstate__(self, dict)
|
| __str__(self)
| Return str(self).
|
| __sub__(self, other)
|
| __truediv__(self, other)
|
| convert(self, domain=None, kind=None, window=None)
| Convert series to a different kind and/or domain and/or window.
|
| Parameters
| ----------
| domain : array_like, optional
| The domain of the converted series. If the value is None,
| the default domain of `kind` is used.
| kind : class, optional
| The polynomial series type class to which the current instance
| should be converted. If kind is None, then the class of the
| current instance is used.
| window : array_like, optional
| The window of the converted series. If the value is None,
| the default window of `kind` is used.
|
| Returns
| -------
| new_series : series
| The returned class can be of different type than the current
| instance and/or have a different domain and/or different
| window.
|
| Notes
| -----
| Conversion between domains and class types can result in
| numerically ill defined series.
|
| copy(self)
| Return a copy.
|
| Returns
| -------
| new_series : series
| Copy of self.
|
| cutdeg(self, deg)
| Truncate series to the given degree.
|
| Reduce the degree of the series to `deg` by discarding the
| high order terms. If `deg` is greater than the current degree a
| copy of the current series is returned. This can be useful in least
| squares where the coefficients of the high degree terms may be very
| small.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| deg : non-negative int
| The series is reduced to degree `deg` by discarding the high
| order terms. The value of `deg` must be a non-negative integer.
|
| Returns
| -------
| new_series : series
| New instance of series with reduced degree.
|
| degree(self)
| The degree of the series.
|
| .. versionadded:: 1.5.0
|
| Returns
| -------
| degree : int
| Degree of the series, one less than the number of coefficients.
|
| Examples
| --------
|
| Create a polynomial object for ``1 + 7*x + 4*x**2``:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 4])
| >>> print(poly)
| 1.0 + 7.0·x + 4.0·x²
| >>> poly.degree()
| 2
|
| Note that this method does not check for non-zero coefficients.
| You must trim the polynomial to remove any trailing zeroes:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 0])
| >>> print(poly)
| 1.0 + 7.0·x + 0.0·x²
| >>> poly.degree()
| 2
| >>> poly.trim().degree()
| 1
|
| deriv(self, m=1)
| Differentiate.
|
| Return a series instance of that is the derivative of the current
| series.
|
| Parameters
| ----------
| m : non-negative int
| Find the derivative of order `m`.
|
| Returns
| -------
| new_series : series
| A new series representing the derivative. The domain is the same
| as the domain of the differentiated series.
|
| has_samecoef(self, other)
| Check if coefficients match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``coef`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the coefficients are the same, False otherwise.
|
| has_samedomain(self, other)
| Check if domains match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``domain`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the domains are the same, False otherwise.
|
| has_sametype(self, other)
| Check if types match.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| other : object
| Class instance.
|
| Returns
| -------
| bool : boolean
| True if other is same class as self
|
| has_samewindow(self, other)
| Check if windows match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``window`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the windows are the same, False otherwise.
|
| integ(self, m=1, k=[], lbnd=None)
| Integrate.
|
| Return a series instance that is the definite integral of the
| current series.
|
| Parameters
| ----------
| m : non-negative int
| The number of integrations to perform.
| k : array_like
| Integration constants. The first constant is applied to the
| first integration, the second to the second, and so on. The
| list of values must less than or equal to `m` in length and any
| missing values are set to zero.
| lbnd : Scalar
| The lower bound of the definite integral.
|
| Returns
| -------
| new_series : series
| A new series representing the integral. The domain is the same
| as the domain of the integrated series.
|
| linspace(self, n=100, domain=None)
| Return x, y values at equally spaced points in domain.
|
| Returns the x, y values at `n` linearly spaced points across the
| domain. Here y is the value of the polynomial at the points x. By
| default the domain is the same as that of the series instance.
| This method is intended mostly as a plotting aid.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| n : int, optional
| Number of point pairs to return. The default value is 100.
| domain : {None, array_like}, optional
| If not None, the specified domain is used instead of that of
| the calling instance. It should be of the form ``[beg,end]``.
| The default is None which case the class domain is used.
|
| Returns
| -------
| x, y : ndarray
| x is equal to linspace(self.domain[0], self.domain[1], n) and
| y is the series evaluated at element of x.
|
| mapparms(self)
| Return the mapping parameters.
|
| The returned values define a linear map ``off + scl*x`` that is
| applied to the input arguments before the series is evaluated. The
| map depends on the ``domain`` and ``window``; if the current
| ``domain`` is equal to the ``window`` the resulting map is the
| identity. If the coefficients of the series instance are to be
| used by themselves outside this class, then the linear function
| must be substituted for the ``x`` in the standard representation of
| the base polynomials.
|
| Returns
| -------
| off, scl : float or complex
| The mapping function is defined by ``off + scl*x``.
|
| Notes
| -----
| If the current domain is the interval ``[l1, r1]`` and the window
| is ``[l2, r2]``, then the linear mapping function ``L`` is
| defined by the equations::
|
| L(l1) = l2
| L(r1) = r2
|
| roots(self)
| Return the roots of the series polynomial.
|
| Compute the roots for the series. Note that the accuracy of the
| roots decreases the further outside the `domain` they lie.
|
| Returns
| -------
| roots : ndarray
| Array containing the roots of the series.
|
| trim(self, tol=0)
| Remove trailing coefficients
|
| Remove trailing coefficients until a coefficient is reached whose
| absolute value greater than `tol` or the beginning of the series is
| reached. If all the coefficients would be removed the series is set
| to ``[0]``. A new series instance is returned with the new
| coefficients. The current instance remains unchanged.
|
| Parameters
| ----------
| tol : non-negative number.
| All trailing coefficients less than `tol` will be removed.
|
| Returns
| -------
| new_series : series
| New instance of series with trimmed coefficients.
|
| truncate(self, size)
| Truncate series to length `size`.
|
| Reduce the series to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer. This
| can be useful in least squares where the coefficients of the
| high degree terms may be very small.
|
| Parameters
| ----------
| size : positive int
| The series is reduced to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer.
|
| Returns
| -------
| new_series : series
| New instance of series with truncated coefficients.
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| basis(deg, domain=None, window=None, symbol='x')
| Series basis polynomial of degree `deg`.
|
| Returns the series representing the basis polynomial of degree `deg`.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| deg : int
| Degree of the basis polynomial for the series. Must be >= 0.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series with the coefficient of the `deg` term set to one and
| all others zero.
|
| cast(series, domain=None, window=None)
| Convert series to series of this class.
|
| The `series` is expected to be an instance of some polynomial
| series of one of the types supported by by the numpy.polynomial
| module, but could be some other class that supports the convert
| method.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| series : series
| The series instance to be converted.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
|
| Returns
| -------
| new_series : series
| A series of the same kind as the calling class and equal to
| `series` when evaluated.
|
| See Also
| --------
| convert : similar instance method
|
| fit(x, y, deg, domain=None, rcond=None, full=False, w=None, window=None, symbol='x')
| Least squares fit to data.
|
| Return a series instance that is the least squares fit to the data
| `y` sampled at `x`. The domain of the returned instance can be
| specified and this will often result in a superior fit with less
| chance of ill conditioning.
|
| Parameters
| ----------
| x : array_like, shape (M,)
| x-coordinates of the M sample points ``(x[i], y[i])``.
| y : array_like, shape (M,)
| y-coordinates of the M sample points ``(x[i], y[i])``.
| deg : int or 1-D array_like
| Degree(s) of the fitting polynomials. If `deg` is a single integer
| all terms up to and including the `deg`'th term are included in the
| fit. For NumPy versions >= 1.11.0 a list of integers specifying the
| degrees of the terms to include may be used instead.
| domain : {None, [beg, end], []}, optional
| Domain to use for the returned series. If ``None``,
| then a minimal domain that covers the points `x` is chosen. If
| ``[]`` the class domain is used. The default value was the
| class domain in NumPy 1.4 and ``None`` in later versions.
| The ``[]`` option was added in numpy 1.5.0.
| rcond : float, 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.
| full : bool, 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.
| w : array_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.
|
| .. versionadded:: 1.5.0
| window : {[beg, end]}, optional
| Window to use for the returned series. The default
| value is the default class domain
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series that represents the least squares fit to the data and
| has the domain and window specified in the call. If the
| coefficients for the unscaled and unshifted basis polynomials are
| of interest, do ``new_series.convert().coef``.
|
| [resid, rank, sv, rcond] : list
| These values are only returned if ``full == True``
|
| - resid -- sum of squared residuals of the least squares fit
| - rank -- the numerical rank of the scaled Vandermonde matrix
| - sv -- singular values of the scaled Vandermonde matrix
| - rcond -- value of `rcond`.
|
| For more details, see `linalg.lstsq`.
|
| fromroots(roots, domain=[], window=None, symbol='x')
| Return series instance that has the specified roots.
|
| Returns a series representing the product
| ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
| list of roots.
|
| Parameters
| ----------
| roots : array_like
| List of roots.
| domain : {[], None, array_like}, optional
| Domain for the resulting series. If None the domain is the
| interval from the smallest root to the largest. If [] the
| domain is the class domain. The default is [].
| window : {None, array_like}, optional
| Window for the returned series. If None the class window is
| used. The default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series with the specified roots.
|
| identity(domain=None, window=None, symbol='x')
| Identity function.
|
| If ``p`` is the returned series, then ``p(x) == x`` for all
| values of x.
|
| Parameters
| ----------
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series of representing the identity.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| symbol
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __array_ufunc__ = None
|
| __hash__ = None
|
| maxpower = 100
class Laguerre(numpy.polynomial._polybase.ABCPolyBase)
| Laguerre(coef, domain=None, window=None, symbol='x')
|
| A Laguerre series class.
|
| The Laguerre class provides the standard Python numerical methods
| '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
| attributes and methods listed below.
|
| Parameters
| ----------
| coef : array_like
| Laguerre coefficients in order of increasing degree, i.e,
| ``(1, 2, 3)`` gives ``1*L_0(x) + 2*L_1(X) + 3*L_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 [0., 1.].
| window : (2,) array_like, optional
| Window, see `domain` for its use. The default value is [0., 1.].
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol used to represent the independent variable in string
| representations of the polynomial expression, e.g. for printing.
| The symbol must be a valid Python identifier. Default value is 'x'.
|
| .. versionadded:: 1.24
|
| Method resolution order:
| Laguerre
| numpy.polynomial._polybase.ABCPolyBase
| abc.ABC
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| basis_name = 'L'
|
| domain = array([0., 1.])
|
| window = array([0., 1.])
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __add__(self, other)
|
| __call__(self, arg)
| Call self as a function.
|
| __divmod__(self, other)
|
| __eq__(self, other)
| Return self==value.
|
| __floordiv__(self, other)
|
| __format__(self, fmt_str)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, coef, domain=None, window=None, symbol='x')
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self)
|
| __len__(self)
|
| __mod__(self, other)
|
| __mul__(self, other)
|
| __ne__(self, other)
| Return self!=value.
|
| __neg__(self)
|
| __pos__(self)
|
| __pow__(self, other)
|
| __radd__(self, other)
|
| __rdiv__(self, other)
|
| __rdivmod__(self, other)
|
| __repr__(self)
| Return repr(self).
|
| __rfloordiv__(self, other)
|
| __rmod__(self, other)
|
| __rmul__(self, other)
|
| __rsub__(self, other)
|
| __rtruediv__(self, other)
|
| __setstate__(self, dict)
|
| __str__(self)
| Return str(self).
|
| __sub__(self, other)
|
| __truediv__(self, other)
|
| convert(self, domain=None, kind=None, window=None)
| Convert series to a different kind and/or domain and/or window.
|
| Parameters
| ----------
| domain : array_like, optional
| The domain of the converted series. If the value is None,
| the default domain of `kind` is used.
| kind : class, optional
| The polynomial series type class to which the current instance
| should be converted. If kind is None, then the class of the
| current instance is used.
| window : array_like, optional
| The window of the converted series. If the value is None,
| the default window of `kind` is used.
|
| Returns
| -------
| new_series : series
| The returned class can be of different type than the current
| instance and/or have a different domain and/or different
| window.
|
| Notes
| -----
| Conversion between domains and class types can result in
| numerically ill defined series.
|
| copy(self)
| Return a copy.
|
| Returns
| -------
| new_series : series
| Copy of self.
|
| cutdeg(self, deg)
| Truncate series to the given degree.
|
| Reduce the degree of the series to `deg` by discarding the
| high order terms. If `deg` is greater than the current degree a
| copy of the current series is returned. This can be useful in least
| squares where the coefficients of the high degree terms may be very
| small.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| deg : non-negative int
| The series is reduced to degree `deg` by discarding the high
| order terms. The value of `deg` must be a non-negative integer.
|
| Returns
| -------
| new_series : series
| New instance of series with reduced degree.
|
| degree(self)
| The degree of the series.
|
| .. versionadded:: 1.5.0
|
| Returns
| -------
| degree : int
| Degree of the series, one less than the number of coefficients.
|
| Examples
| --------
|
| Create a polynomial object for ``1 + 7*x + 4*x**2``:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 4])
| >>> print(poly)
| 1.0 + 7.0·x + 4.0·x²
| >>> poly.degree()
| 2
|
| Note that this method does not check for non-zero coefficients.
| You must trim the polynomial to remove any trailing zeroes:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 0])
| >>> print(poly)
| 1.0 + 7.0·x + 0.0·x²
| >>> poly.degree()
| 2
| >>> poly.trim().degree()
| 1
|
| deriv(self, m=1)
| Differentiate.
|
| Return a series instance of that is the derivative of the current
| series.
|
| Parameters
| ----------
| m : non-negative int
| Find the derivative of order `m`.
|
| Returns
| -------
| new_series : series
| A new series representing the derivative. The domain is the same
| as the domain of the differentiated series.
|
| has_samecoef(self, other)
| Check if coefficients match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``coef`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the coefficients are the same, False otherwise.
|
| has_samedomain(self, other)
| Check if domains match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``domain`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the domains are the same, False otherwise.
|
| has_sametype(self, other)
| Check if types match.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| other : object
| Class instance.
|
| Returns
| -------
| bool : boolean
| True if other is same class as self
|
| has_samewindow(self, other)
| Check if windows match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``window`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the windows are the same, False otherwise.
|
| integ(self, m=1, k=[], lbnd=None)
| Integrate.
|
| Return a series instance that is the definite integral of the
| current series.
|
| Parameters
| ----------
| m : non-negative int
| The number of integrations to perform.
| k : array_like
| Integration constants. The first constant is applied to the
| first integration, the second to the second, and so on. The
| list of values must less than or equal to `m` in length and any
| missing values are set to zero.
| lbnd : Scalar
| The lower bound of the definite integral.
|
| Returns
| -------
| new_series : series
| A new series representing the integral. The domain is the same
| as the domain of the integrated series.
|
| linspace(self, n=100, domain=None)
| Return x, y values at equally spaced points in domain.
|
| Returns the x, y values at `n` linearly spaced points across the
| domain. Here y is the value of the polynomial at the points x. By
| default the domain is the same as that of the series instance.
| This method is intended mostly as a plotting aid.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| n : int, optional
| Number of point pairs to return. The default value is 100.
| domain : {None, array_like}, optional
| If not None, the specified domain is used instead of that of
| the calling instance. It should be of the form ``[beg,end]``.
| The default is None which case the class domain is used.
|
| Returns
| -------
| x, y : ndarray
| x is equal to linspace(self.domain[0], self.domain[1], n) and
| y is the series evaluated at element of x.
|
| mapparms(self)
| Return the mapping parameters.
|
| The returned values define a linear map ``off + scl*x`` that is
| applied to the input arguments before the series is evaluated. The
| map depends on the ``domain`` and ``window``; if the current
| ``domain`` is equal to the ``window`` the resulting map is the
| identity. If the coefficients of the series instance are to be
| used by themselves outside this class, then the linear function
| must be substituted for the ``x`` in the standard representation of
| the base polynomials.
|
| Returns
| -------
| off, scl : float or complex
| The mapping function is defined by ``off + scl*x``.
|
| Notes
| -----
| If the current domain is the interval ``[l1, r1]`` and the window
| is ``[l2, r2]``, then the linear mapping function ``L`` is
| defined by the equations::
|
| L(l1) = l2
| L(r1) = r2
|
| roots(self)
| Return the roots of the series polynomial.
|
| Compute the roots for the series. Note that the accuracy of the
| roots decreases the further outside the `domain` they lie.
|
| Returns
| -------
| roots : ndarray
| Array containing the roots of the series.
|
| trim(self, tol=0)
| Remove trailing coefficients
|
| Remove trailing coefficients until a coefficient is reached whose
| absolute value greater than `tol` or the beginning of the series is
| reached. If all the coefficients would be removed the series is set
| to ``[0]``. A new series instance is returned with the new
| coefficients. The current instance remains unchanged.
|
| Parameters
| ----------
| tol : non-negative number.
| All trailing coefficients less than `tol` will be removed.
|
| Returns
| -------
| new_series : series
| New instance of series with trimmed coefficients.
|
| truncate(self, size)
| Truncate series to length `size`.
|
| Reduce the series to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer. This
| can be useful in least squares where the coefficients of the
| high degree terms may be very small.
|
| Parameters
| ----------
| size : positive int
| The series is reduced to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer.
|
| Returns
| -------
| new_series : series
| New instance of series with truncated coefficients.
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| basis(deg, domain=None, window=None, symbol='x')
| Series basis polynomial of degree `deg`.
|
| Returns the series representing the basis polynomial of degree `deg`.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| deg : int
| Degree of the basis polynomial for the series. Must be >= 0.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series with the coefficient of the `deg` term set to one and
| all others zero.
|
| cast(series, domain=None, window=None)
| Convert series to series of this class.
|
| The `series` is expected to be an instance of some polynomial
| series of one of the types supported by by the numpy.polynomial
| module, but could be some other class that supports the convert
| method.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| series : series
| The series instance to be converted.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
|
| Returns
| -------
| new_series : series
| A series of the same kind as the calling class and equal to
| `series` when evaluated.
|
| See Also
| --------
| convert : similar instance method
|
| fit(x, y, deg, domain=None, rcond=None, full=False, w=None, window=None, symbol='x')
| Least squares fit to data.
|
| Return a series instance that is the least squares fit to the data
| `y` sampled at `x`. The domain of the returned instance can be
| specified and this will often result in a superior fit with less
| chance of ill conditioning.
|
| Parameters
| ----------
| x : array_like, shape (M,)
| x-coordinates of the M sample points ``(x[i], y[i])``.
| y : array_like, shape (M,)
| y-coordinates of the M sample points ``(x[i], y[i])``.
| deg : int or 1-D array_like
| Degree(s) of the fitting polynomials. If `deg` is a single integer
| all terms up to and including the `deg`'th term are included in the
| fit. For NumPy versions >= 1.11.0 a list of integers specifying the
| degrees of the terms to include may be used instead.
| domain : {None, [beg, end], []}, optional
| Domain to use for the returned series. If ``None``,
| then a minimal domain that covers the points `x` is chosen. If
| ``[]`` the class domain is used. The default value was the
| class domain in NumPy 1.4 and ``None`` in later versions.
| The ``[]`` option was added in numpy 1.5.0.
| rcond : float, 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.
| full : bool, 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.
| w : array_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.
|
| .. versionadded:: 1.5.0
| window : {[beg, end]}, optional
| Window to use for the returned series. The default
| value is the default class domain
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series that represents the least squares fit to the data and
| has the domain and window specified in the call. If the
| coefficients for the unscaled and unshifted basis polynomials are
| of interest, do ``new_series.convert().coef``.
|
| [resid, rank, sv, rcond] : list
| These values are only returned if ``full == True``
|
| - resid -- sum of squared residuals of the least squares fit
| - rank -- the numerical rank of the scaled Vandermonde matrix
| - sv -- singular values of the scaled Vandermonde matrix
| - rcond -- value of `rcond`.
|
| For more details, see `linalg.lstsq`.
|
| fromroots(roots, domain=[], window=None, symbol='x')
| Return series instance that has the specified roots.
|
| Returns a series representing the product
| ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
| list of roots.
|
| Parameters
| ----------
| roots : array_like
| List of roots.
| domain : {[], None, array_like}, optional
| Domain for the resulting series. If None the domain is the
| interval from the smallest root to the largest. If [] the
| domain is the class domain. The default is [].
| window : {None, array_like}, optional
| Window for the returned series. If None the class window is
| used. The default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series with the specified roots.
|
| identity(domain=None, window=None, symbol='x')
| Identity function.
|
| If ``p`` is the returned series, then ``p(x) == x`` for all
| values of x.
|
| Parameters
| ----------
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series of representing the identity.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| symbol
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __array_ufunc__ = None
|
| __hash__ = None
|
| maxpower = 100
class Legendre(numpy.polynomial._polybase.ABCPolyBase)
| Legendre(coef, domain=None, window=None, symbol='x')
|
| A Legendre series class.
|
| The Legendre class provides the standard Python numerical methods
| '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
| attributes and methods listed below.
|
| Parameters
| ----------
| coef : array_like
| Legendre coefficients in order of increasing degree, i.e.,
| ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``.
| domain : (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.].
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol used to represent the independent variable in string
| representations of the polynomial expression, e.g. for printing.
| The symbol must be a valid Python identifier. Default value is 'x'.
|
| .. versionadded:: 1.24
|
| Method resolution order:
| Legendre
| numpy.polynomial._polybase.ABCPolyBase
| abc.ABC
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| basis_name = 'P'
|
| domain = array([-1., 1.])
|
| window = array([-1., 1.])
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __add__(self, other)
|
| __call__(self, arg)
| Call self as a function.
|
| __divmod__(self, other)
|
| __eq__(self, other)
| Return self==value.
|
| __floordiv__(self, other)
|
| __format__(self, fmt_str)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, coef, domain=None, window=None, symbol='x')
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self)
|
| __len__(self)
|
| __mod__(self, other)
|
| __mul__(self, other)
|
| __ne__(self, other)
| Return self!=value.
|
| __neg__(self)
|
| __pos__(self)
|
| __pow__(self, other)
|
| __radd__(self, other)
|
| __rdiv__(self, other)
|
| __rdivmod__(self, other)
|
| __repr__(self)
| Return repr(self).
|
| __rfloordiv__(self, other)
|
| __rmod__(self, other)
|
| __rmul__(self, other)
|
| __rsub__(self, other)
|
| __rtruediv__(self, other)
|
| __setstate__(self, dict)
|
| __str__(self)
| Return str(self).
|
| __sub__(self, other)
|
| __truediv__(self, other)
|
| convert(self, domain=None, kind=None, window=None)
| Convert series to a different kind and/or domain and/or window.
|
| Parameters
| ----------
| domain : array_like, optional
| The domain of the converted series. If the value is None,
| the default domain of `kind` is used.
| kind : class, optional
| The polynomial series type class to which the current instance
| should be converted. If kind is None, then the class of the
| current instance is used.
| window : array_like, optional
| The window of the converted series. If the value is None,
| the default window of `kind` is used.
|
| Returns
| -------
| new_series : series
| The returned class can be of different type than the current
| instance and/or have a different domain and/or different
| window.
|
| Notes
| -----
| Conversion between domains and class types can result in
| numerically ill defined series.
|
| copy(self)
| Return a copy.
|
| Returns
| -------
| new_series : series
| Copy of self.
|
| cutdeg(self, deg)
| Truncate series to the given degree.
|
| Reduce the degree of the series to `deg` by discarding the
| high order terms. If `deg` is greater than the current degree a
| copy of the current series is returned. This can be useful in least
| squares where the coefficients of the high degree terms may be very
| small.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| deg : non-negative int
| The series is reduced to degree `deg` by discarding the high
| order terms. The value of `deg` must be a non-negative integer.
|
| Returns
| -------
| new_series : series
| New instance of series with reduced degree.
|
| degree(self)
| The degree of the series.
|
| .. versionadded:: 1.5.0
|
| Returns
| -------
| degree : int
| Degree of the series, one less than the number of coefficients.
|
| Examples
| --------
|
| Create a polynomial object for ``1 + 7*x + 4*x**2``:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 4])
| >>> print(poly)
| 1.0 + 7.0·x + 4.0·x²
| >>> poly.degree()
| 2
|
| Note that this method does not check for non-zero coefficients.
| You must trim the polynomial to remove any trailing zeroes:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 0])
| >>> print(poly)
| 1.0 + 7.0·x + 0.0·x²
| >>> poly.degree()
| 2
| >>> poly.trim().degree()
| 1
|
| deriv(self, m=1)
| Differentiate.
|
| Return a series instance of that is the derivative of the current
| series.
|
| Parameters
| ----------
| m : non-negative int
| Find the derivative of order `m`.
|
| Returns
| -------
| new_series : series
| A new series representing the derivative. The domain is the same
| as the domain of the differentiated series.
|
| has_samecoef(self, other)
| Check if coefficients match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``coef`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the coefficients are the same, False otherwise.
|
| has_samedomain(self, other)
| Check if domains match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``domain`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the domains are the same, False otherwise.
|
| has_sametype(self, other)
| Check if types match.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| other : object
| Class instance.
|
| Returns
| -------
| bool : boolean
| True if other is same class as self
|
| has_samewindow(self, other)
| Check if windows match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``window`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the windows are the same, False otherwise.
|
| integ(self, m=1, k=[], lbnd=None)
| Integrate.
|
| Return a series instance that is the definite integral of the
| current series.
|
| Parameters
| ----------
| m : non-negative int
| The number of integrations to perform.
| k : array_like
| Integration constants. The first constant is applied to the
| first integration, the second to the second, and so on. The
| list of values must less than or equal to `m` in length and any
| missing values are set to zero.
| lbnd : Scalar
| The lower bound of the definite integral.
|
| Returns
| -------
| new_series : series
| A new series representing the integral. The domain is the same
| as the domain of the integrated series.
|
| linspace(self, n=100, domain=None)
| Return x, y values at equally spaced points in domain.
|
| Returns the x, y values at `n` linearly spaced points across the
| domain. Here y is the value of the polynomial at the points x. By
| default the domain is the same as that of the series instance.
| This method is intended mostly as a plotting aid.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| n : int, optional
| Number of point pairs to return. The default value is 100.
| domain : {None, array_like}, optional
| If not None, the specified domain is used instead of that of
| the calling instance. It should be of the form ``[beg,end]``.
| The default is None which case the class domain is used.
|
| Returns
| -------
| x, y : ndarray
| x is equal to linspace(self.domain[0], self.domain[1], n) and
| y is the series evaluated at element of x.
|
| mapparms(self)
| Return the mapping parameters.
|
| The returned values define a linear map ``off + scl*x`` that is
| applied to the input arguments before the series is evaluated. The
| map depends on the ``domain`` and ``window``; if the current
| ``domain`` is equal to the ``window`` the resulting map is the
| identity. If the coefficients of the series instance are to be
| used by themselves outside this class, then the linear function
| must be substituted for the ``x`` in the standard representation of
| the base polynomials.
|
| Returns
| -------
| off, scl : float or complex
| The mapping function is defined by ``off + scl*x``.
|
| Notes
| -----
| If the current domain is the interval ``[l1, r1]`` and the window
| is ``[l2, r2]``, then the linear mapping function ``L`` is
| defined by the equations::
|
| L(l1) = l2
| L(r1) = r2
|
| roots(self)
| Return the roots of the series polynomial.
|
| Compute the roots for the series. Note that the accuracy of the
| roots decreases the further outside the `domain` they lie.
|
| Returns
| -------
| roots : ndarray
| Array containing the roots of the series.
|
| trim(self, tol=0)
| Remove trailing coefficients
|
| Remove trailing coefficients until a coefficient is reached whose
| absolute value greater than `tol` or the beginning of the series is
| reached. If all the coefficients would be removed the series is set
| to ``[0]``. A new series instance is returned with the new
| coefficients. The current instance remains unchanged.
|
| Parameters
| ----------
| tol : non-negative number.
| All trailing coefficients less than `tol` will be removed.
|
| Returns
| -------
| new_series : series
| New instance of series with trimmed coefficients.
|
| truncate(self, size)
| Truncate series to length `size`.
|
| Reduce the series to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer. This
| can be useful in least squares where the coefficients of the
| high degree terms may be very small.
|
| Parameters
| ----------
| size : positive int
| The series is reduced to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer.
|
| Returns
| -------
| new_series : series
| New instance of series with truncated coefficients.
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| basis(deg, domain=None, window=None, symbol='x')
| Series basis polynomial of degree `deg`.
|
| Returns the series representing the basis polynomial of degree `deg`.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| deg : int
| Degree of the basis polynomial for the series. Must be >= 0.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series with the coefficient of the `deg` term set to one and
| all others zero.
|
| cast(series, domain=None, window=None)
| Convert series to series of this class.
|
| The `series` is expected to be an instance of some polynomial
| series of one of the types supported by by the numpy.polynomial
| module, but could be some other class that supports the convert
| method.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| series : series
| The series instance to be converted.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
|
| Returns
| -------
| new_series : series
| A series of the same kind as the calling class and equal to
| `series` when evaluated.
|
| See Also
| --------
| convert : similar instance method
|
| fit(x, y, deg, domain=None, rcond=None, full=False, w=None, window=None, symbol='x')
| Least squares fit to data.
|
| Return a series instance that is the least squares fit to the data
| `y` sampled at `x`. The domain of the returned instance can be
| specified and this will often result in a superior fit with less
| chance of ill conditioning.
|
| Parameters
| ----------
| x : array_like, shape (M,)
| x-coordinates of the M sample points ``(x[i], y[i])``.
| y : array_like, shape (M,)
| y-coordinates of the M sample points ``(x[i], y[i])``.
| deg : int or 1-D array_like
| Degree(s) of the fitting polynomials. If `deg` is a single integer
| all terms up to and including the `deg`'th term are included in the
| fit. For NumPy versions >= 1.11.0 a list of integers specifying the
| degrees of the terms to include may be used instead.
| domain : {None, [beg, end], []}, optional
| Domain to use for the returned series. If ``None``,
| then a minimal domain that covers the points `x` is chosen. If
| ``[]`` the class domain is used. The default value was the
| class domain in NumPy 1.4 and ``None`` in later versions.
| The ``[]`` option was added in numpy 1.5.0.
| rcond : float, 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.
| full : bool, 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.
| w : array_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.
|
| .. versionadded:: 1.5.0
| window : {[beg, end]}, optional
| Window to use for the returned series. The default
| value is the default class domain
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series that represents the least squares fit to the data and
| has the domain and window specified in the call. If the
| coefficients for the unscaled and unshifted basis polynomials are
| of interest, do ``new_series.convert().coef``.
|
| [resid, rank, sv, rcond] : list
| These values are only returned if ``full == True``
|
| - resid -- sum of squared residuals of the least squares fit
| - rank -- the numerical rank of the scaled Vandermonde matrix
| - sv -- singular values of the scaled Vandermonde matrix
| - rcond -- value of `rcond`.
|
| For more details, see `linalg.lstsq`.
|
| fromroots(roots, domain=[], window=None, symbol='x')
| Return series instance that has the specified roots.
|
| Returns a series representing the product
| ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
| list of roots.
|
| Parameters
| ----------
| roots : array_like
| List of roots.
| domain : {[], None, array_like}, optional
| Domain for the resulting series. If None the domain is the
| interval from the smallest root to the largest. If [] the
| domain is the class domain. The default is [].
| window : {None, array_like}, optional
| Window for the returned series. If None the class window is
| used. The default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series with the specified roots.
|
| identity(domain=None, window=None, symbol='x')
| Identity function.
|
| If ``p`` is the returned series, then ``p(x) == x`` for all
| values of x.
|
| Parameters
| ----------
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series of representing the identity.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| symbol
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __array_ufunc__ = None
|
| __hash__ = None
|
| maxpower = 100
class Polynomial(numpy.polynomial._polybase.ABCPolyBase)
| Polynomial(coef, domain=None, window=None, symbol='x')
|
| A power series class.
|
| The Polynomial class provides the standard Python numerical methods
| '+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
| attributes and methods listed below.
|
| Parameters
| ----------
| coef : array_like
| Polynomial coefficients in order of increasing degree, i.e.,
| ``(1, 2, 3)`` give ``1 + 2*x + 3*x**2``.
| 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.].
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol used to represent the independent variable in string
| representations of the polynomial expression, e.g. for printing.
| The symbol must be a valid Python identifier. Default value is 'x'.
|
| .. versionadded:: 1.24
|
| Method resolution order:
| Polynomial
| numpy.polynomial._polybase.ABCPolyBase
| abc.ABC
| builtins.object
|
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| basis_name = None
|
| domain = array([-1., 1.])
|
| window = array([-1., 1.])
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __add__(self, other)
|
| __call__(self, arg)
| Call self as a function.
|
| __divmod__(self, other)
|
| __eq__(self, other)
| Return self==value.
|
| __floordiv__(self, other)
|
| __format__(self, fmt_str)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __getstate__(self)
| Helper for pickle.
|
| __init__(self, coef, domain=None, window=None, symbol='x')
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self)
|
| __len__(self)
|
| __mod__(self, other)
|
| __mul__(self, other)
|
| __ne__(self, other)
| Return self!=value.
|
| __neg__(self)
|
| __pos__(self)
|
| __pow__(self, other)
|
| __radd__(self, other)
|
| __rdiv__(self, other)
|
| __rdivmod__(self, other)
|
| __repr__(self)
| Return repr(self).
|
| __rfloordiv__(self, other)
|
| __rmod__(self, other)
|
| __rmul__(self, other)
|
| __rsub__(self, other)
|
| __rtruediv__(self, other)
|
| __setstate__(self, dict)
|
| __str__(self)
| Return str(self).
|
| __sub__(self, other)
|
| __truediv__(self, other)
|
| convert(self, domain=None, kind=None, window=None)
| Convert series to a different kind and/or domain and/or window.
|
| Parameters
| ----------
| domain : array_like, optional
| The domain of the converted series. If the value is None,
| the default domain of `kind` is used.
| kind : class, optional
| The polynomial series type class to which the current instance
| should be converted. If kind is None, then the class of the
| current instance is used.
| window : array_like, optional
| The window of the converted series. If the value is None,
| the default window of `kind` is used.
|
| Returns
| -------
| new_series : series
| The returned class can be of different type than the current
| instance and/or have a different domain and/or different
| window.
|
| Notes
| -----
| Conversion between domains and class types can result in
| numerically ill defined series.
|
| copy(self)
| Return a copy.
|
| Returns
| -------
| new_series : series
| Copy of self.
|
| cutdeg(self, deg)
| Truncate series to the given degree.
|
| Reduce the degree of the series to `deg` by discarding the
| high order terms. If `deg` is greater than the current degree a
| copy of the current series is returned. This can be useful in least
| squares where the coefficients of the high degree terms may be very
| small.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| deg : non-negative int
| The series is reduced to degree `deg` by discarding the high
| order terms. The value of `deg` must be a non-negative integer.
|
| Returns
| -------
| new_series : series
| New instance of series with reduced degree.
|
| degree(self)
| The degree of the series.
|
| .. versionadded:: 1.5.0
|
| Returns
| -------
| degree : int
| Degree of the series, one less than the number of coefficients.
|
| Examples
| --------
|
| Create a polynomial object for ``1 + 7*x + 4*x**2``:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 4])
| >>> print(poly)
| 1.0 + 7.0·x + 4.0·x²
| >>> poly.degree()
| 2
|
| Note that this method does not check for non-zero coefficients.
| You must trim the polynomial to remove any trailing zeroes:
|
| >>> poly = np.polynomial.Polynomial([1, 7, 0])
| >>> print(poly)
| 1.0 + 7.0·x + 0.0·x²
| >>> poly.degree()
| 2
| >>> poly.trim().degree()
| 1
|
| deriv(self, m=1)
| Differentiate.
|
| Return a series instance of that is the derivative of the current
| series.
|
| Parameters
| ----------
| m : non-negative int
| Find the derivative of order `m`.
|
| Returns
| -------
| new_series : series
| A new series representing the derivative. The domain is the same
| as the domain of the differentiated series.
|
| has_samecoef(self, other)
| Check if coefficients match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``coef`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the coefficients are the same, False otherwise.
|
| has_samedomain(self, other)
| Check if domains match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``domain`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the domains are the same, False otherwise.
|
| has_sametype(self, other)
| Check if types match.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| other : object
| Class instance.
|
| Returns
| -------
| bool : boolean
| True if other is same class as self
|
| has_samewindow(self, other)
| Check if windows match.
|
| .. versionadded:: 1.6.0
|
| Parameters
| ----------
| other : class instance
| The other class must have the ``window`` attribute.
|
| Returns
| -------
| bool : boolean
| True if the windows are the same, False otherwise.
|
| integ(self, m=1, k=[], lbnd=None)
| Integrate.
|
| Return a series instance that is the definite integral of the
| current series.
|
| Parameters
| ----------
| m : non-negative int
| The number of integrations to perform.
| k : array_like
| Integration constants. The first constant is applied to the
| first integration, the second to the second, and so on. The
| list of values must less than or equal to `m` in length and any
| missing values are set to zero.
| lbnd : Scalar
| The lower bound of the definite integral.
|
| Returns
| -------
| new_series : series
| A new series representing the integral. The domain is the same
| as the domain of the integrated series.
|
| linspace(self, n=100, domain=None)
| Return x, y values at equally spaced points in domain.
|
| Returns the x, y values at `n` linearly spaced points across the
| domain. Here y is the value of the polynomial at the points x. By
| default the domain is the same as that of the series instance.
| This method is intended mostly as a plotting aid.
|
| .. versionadded:: 1.5.0
|
| Parameters
| ----------
| n : int, optional
| Number of point pairs to return. The default value is 100.
| domain : {None, array_like}, optional
| If not None, the specified domain is used instead of that of
| the calling instance. It should be of the form ``[beg,end]``.
| The default is None which case the class domain is used.
|
| Returns
| -------
| x, y : ndarray
| x is equal to linspace(self.domain[0], self.domain[1], n) and
| y is the series evaluated at element of x.
|
| mapparms(self)
| Return the mapping parameters.
|
| The returned values define a linear map ``off + scl*x`` that is
| applied to the input arguments before the series is evaluated. The
| map depends on the ``domain`` and ``window``; if the current
| ``domain`` is equal to the ``window`` the resulting map is the
| identity. If the coefficients of the series instance are to be
| used by themselves outside this class, then the linear function
| must be substituted for the ``x`` in the standard representation of
| the base polynomials.
|
| Returns
| -------
| off, scl : float or complex
| The mapping function is defined by ``off + scl*x``.
|
| Notes
| -----
| If the current domain is the interval ``[l1, r1]`` and the window
| is ``[l2, r2]``, then the linear mapping function ``L`` is
| defined by the equations::
|
| L(l1) = l2
| L(r1) = r2
|
| roots(self)
| Return the roots of the series polynomial.
|
| Compute the roots for the series. Note that the accuracy of the
| roots decreases the further outside the `domain` they lie.
|
| Returns
| -------
| roots : ndarray
| Array containing the roots of the series.
|
| trim(self, tol=0)
| Remove trailing coefficients
|
| Remove trailing coefficients until a coefficient is reached whose
| absolute value greater than `tol` or the beginning of the series is
| reached. If all the coefficients would be removed the series is set
| to ``[0]``. A new series instance is returned with the new
| coefficients. The current instance remains unchanged.
|
| Parameters
| ----------
| tol : non-negative number.
| All trailing coefficients less than `tol` will be removed.
|
| Returns
| -------
| new_series : series
| New instance of series with trimmed coefficients.
|
| truncate(self, size)
| Truncate series to length `size`.
|
| Reduce the series to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer. This
| can be useful in least squares where the coefficients of the
| high degree terms may be very small.
|
| Parameters
| ----------
| size : positive int
| The series is reduced to length `size` by discarding the high
| degree terms. The value of `size` must be a positive integer.
|
| Returns
| -------
| new_series : series
| New instance of series with truncated coefficients.
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| basis(deg, domain=None, window=None, symbol='x')
| Series basis polynomial of degree `deg`.
|
| Returns the series representing the basis polynomial of degree `deg`.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| deg : int
| Degree of the basis polynomial for the series. Must be >= 0.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series with the coefficient of the `deg` term set to one and
| all others zero.
|
| cast(series, domain=None, window=None)
| Convert series to series of this class.
|
| The `series` is expected to be an instance of some polynomial
| series of one of the types supported by by the numpy.polynomial
| module, but could be some other class that supports the convert
| method.
|
| .. versionadded:: 1.7.0
|
| Parameters
| ----------
| series : series
| The series instance to be converted.
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
|
| Returns
| -------
| new_series : series
| A series of the same kind as the calling class and equal to
| `series` when evaluated.
|
| See Also
| --------
| convert : similar instance method
|
| fit(x, y, deg, domain=None, rcond=None, full=False, w=None, window=None, symbol='x')
| Least squares fit to data.
|
| Return a series instance that is the least squares fit to the data
| `y` sampled at `x`. The domain of the returned instance can be
| specified and this will often result in a superior fit with less
| chance of ill conditioning.
|
| Parameters
| ----------
| x : array_like, shape (M,)
| x-coordinates of the M sample points ``(x[i], y[i])``.
| y : array_like, shape (M,)
| y-coordinates of the M sample points ``(x[i], y[i])``.
| deg : int or 1-D array_like
| Degree(s) of the fitting polynomials. If `deg` is a single integer
| all terms up to and including the `deg`'th term are included in the
| fit. For NumPy versions >= 1.11.0 a list of integers specifying the
| degrees of the terms to include may be used instead.
| domain : {None, [beg, end], []}, optional
| Domain to use for the returned series. If ``None``,
| then a minimal domain that covers the points `x` is chosen. If
| ``[]`` the class domain is used. The default value was the
| class domain in NumPy 1.4 and ``None`` in later versions.
| The ``[]`` option was added in numpy 1.5.0.
| rcond : float, 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.
| full : bool, 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.
| w : array_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.
|
| .. versionadded:: 1.5.0
| window : {[beg, end]}, optional
| Window to use for the returned series. The default
| value is the default class domain
|
| .. versionadded:: 1.6.0
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| A series that represents the least squares fit to the data and
| has the domain and window specified in the call. If the
| coefficients for the unscaled and unshifted basis polynomials are
| of interest, do ``new_series.convert().coef``.
|
| [resid, rank, sv, rcond] : list
| These values are only returned if ``full == True``
|
| - resid -- sum of squared residuals of the least squares fit
| - rank -- the numerical rank of the scaled Vandermonde matrix
| - sv -- singular values of the scaled Vandermonde matrix
| - rcond -- value of `rcond`.
|
| For more details, see `linalg.lstsq`.
|
| fromroots(roots, domain=[], window=None, symbol='x')
| Return series instance that has the specified roots.
|
| Returns a series representing the product
| ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
| list of roots.
|
| Parameters
| ----------
| roots : array_like
| List of roots.
| domain : {[], None, array_like}, optional
| Domain for the resulting series. If None the domain is the
| interval from the smallest root to the largest. If [] the
| domain is the class domain. The default is [].
| window : {None, array_like}, optional
| Window for the returned series. If None the class window is
| used. The default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series with the specified roots.
|
| identity(domain=None, window=None, symbol='x')
| Identity function.
|
| If ``p`` is the returned series, then ``p(x) == x`` for all
| values of x.
|
| Parameters
| ----------
| domain : {None, array_like}, optional
| If given, the array must be of the form ``[beg, end]``, where
| ``beg`` and ``end`` are the endpoints of the domain. If None is
| given then the class domain is used. The default is None.
| window : {None, array_like}, optional
| If given, the resulting array must be if the form
| ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
| the window. If None is given then the class window is used. The
| default is None.
| symbol : str, optional
| Symbol representing the independent variable. Default is 'x'.
|
| Returns
| -------
| new_series : series
| Series of representing the identity.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| symbol
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.polynomial._polybase.ABCPolyBase:
|
| __array_ufunc__ = None
|
| __hash__ = None
|
| maxpower = 100
FUNCTIONS
set_default_printstyle(style)
Set the default format for the string representation of polynomials.
Values for ``style`` must be valid inputs to ``__format__``, i.e. 'ascii'
or 'unicode'.
Parameters
----------
style : str
Format string for default printing style. Must be either 'ascii' or
'unicode'.
Notes
-----
The default format depends on the platform: 'unicode' is used on
Unix-based systems and 'ascii' on Windows. This determination is based on
default font support for the unicode superscript and subscript ranges.
Examples
--------
>>> p = np.polynomial.Polynomial([1, 2, 3])
>>> c = np.polynomial.Chebyshev([1, 2, 3])
>>> np.polynomial.set_default_printstyle('unicode')
>>> print(p)
1.0 + 2.0·x + 3.0·x²
>>> print(c)
1.0 + 2.0·T₁(x) + 3.0·T₂(x)
>>> np.polynomial.set_default_printstyle('ascii')
>>> print(p)
1.0 + 2.0 x + 3.0 x**2
>>> print(c)
1.0 + 2.0 T_1(x) + 3.0 T_2(x)
>>> # Formatting supersedes all class/package-level defaults
>>> print(f"{p:unicode}")
1.0 + 2.0·x + 3.0·x²
DATA
__all__ = ['set_default_printstyle', 'polynomial', 'Polynomial', 'cheb...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\polynomial\__init__.py
numpy.polysub
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
polysub(a1, a2)
Difference (subtraction) of two polynomials.
.. note::
This forms part of the old polynomial API. Since version 1.4, the
new polynomial API defined in `numpy.polynomial` is preferred.
A summary of the differences can be found in the
:doc:`transition guide </reference/routines.polynomials>`.
Given two polynomials `a1` and `a2`, returns ``a1 - a2``.
`a1` and `a2` can be either array_like sequences of the polynomials'
coefficients (including coefficients equal to zero), or `poly1d` objects.
Parameters
----------
a1, a2 : array_like or poly1d
Minuend and subtrahend polynomials, respectively.
Returns
-------
out : ndarray or poly1d
Array or `poly1d` object of the difference polynomial's coefficients.
See Also
--------
polyval, polydiv, polymul, polyadd
Examples
--------
.. math:: (2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2)
>>> import numpy as np
>>> np.polysub([2, 10, -2], [3, 10, -4])
array([-1, 0, 2])
numpy.polyval
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
polyval(p, x)
Evaluate a polynomial at specific values.
.. note::
This forms part of the old polynomial API. Since version 1.4, the
new polynomial API defined in `numpy.polynomial` is preferred.
A summary of the differences can be found in the
:doc:`transition guide </reference/routines.polynomials>`.
If `p` is of length N, this function returns the value::
p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]
If `x` is a sequence, then ``p(x)`` is returned for each element of ``x``.
If `x` is another polynomial then the composite polynomial ``p(x(t))``
is returned.
Parameters
----------
p : array_like or poly1d object
1D array of polynomial coefficients (including coefficients equal
to zero) from highest degree to the constant term, or an
instance of poly1d.
x : array_like or poly1d object
A number, an array of numbers, or an instance of poly1d, at
which to evaluate `p`.
Returns
-------
values : ndarray or poly1d
If `x` is a poly1d instance, the result is the composition of the two
polynomials, i.e., `x` is "substituted" in `p` and the simplified
result is returned. In addition, the type of `x` - array_like or
poly1d - governs the type of the output: `x` array_like => `values`
array_like, `x` a poly1d object => `values` is also.
See Also
--------
poly1d: A polynomial class.
Notes
-----
Horner's scheme [1]_ is used to evaluate the polynomial. Even so,
for polynomials of high degree the values may be inaccurate due to
rounding errors. Use carefully.
If `x` is a subtype of `ndarray` the return value will be of the same type.
References
----------
.. [1] I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng.
trans. Ed.), *Handbook of Mathematics*, New York, Van Nostrand
Reinhold Co., 1985, pg. 720.
Examples
--------
>>> import numpy as np
>>> np.polyval([3,0,1], 5) # 3 * 5**2 + 0 * 5**1 + 1
76
>>> np.polyval([3,0,1], np.poly1d(5))
poly1d([76])
>>> np.polyval(np.poly1d([3,0,1]), 5)
76
>>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
poly1d([76])
numpy.positive
Python Library Documentation: ufunc
positive = <ufunc 'positive'>
positive(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Numerical positive, element-wise.
.. versionadded:: 1.13.0
Parameters
----------
x : array_like or scalar
Input array.
Returns
-------
y : ndarray or scalar
Returned array or scalar: `y = +x`.
This is a scalar if `x` is a scalar.
Notes
-----
Equivalent to `x.copy()`, but only defined for types that support
arithmetic.
Examples
--------
>>> import numpy as np
>>> x1 = np.array(([1., -1.]))
>>> np.positive(x1)
array([ 1., -1.])
The unary ``+`` operator can be used as a shorthand for ``np.positive`` on
ndarrays.
>>> x1 = np.array(([1., -1.]))
>>> +x1
array([ 1., -1.])
numpy.pow
Python Library Documentation: ufunc
power = <ufunc 'power'>
power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
First array elements raised to powers from second array, element-wise.
Raise each base in `x1` to the positionally-corresponding power in
`x2`. `x1` and `x2` must be broadcastable to the same shape.
An integer type raised to a negative integer power will raise a
``ValueError``.
Negative values raised to a non-integral value will return ``nan``.
To get complex results, cast the input to complex, or specify the
``dtype`` to be ``complex`` (see the example below).
Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
float_power : power function that promotes integers to float
Examples
--------
>>> import numpy as np
Cube each element in an array.
>>> x1 = np.arange(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([ 0, 1, 8, 27, 64, 125])
Raise the bases to different exponents.
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([ 0., 1., 8., 27., 16., 5.])
The effect of broadcasting.
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0, 1, 8, 27, 16, 5],
[ 0, 1, 8, 27, 16, 5]])
The ``**`` operator can be used as a shorthand for ``np.power`` on
ndarrays.
>>> x2 = np.array([1, 2, 3, 3, 2, 1])
>>> x1 = np.arange(6)
>>> x1 ** x2
array([ 0, 1, 8, 27, 16, 5])
Negative values raised to a non-integral value will result in ``nan``
(and a warning will be generated).
>>> x3 = np.array([-1.0, -4.0])
>>> with np.errstate(invalid='ignore'):
... p = np.power(x3, 1.5)
...
>>> p
array([nan, nan])
To get complex results, give the argument ``dtype=complex``.
>>> np.power(x3, 1.5, dtype=complex)
array([-1.83697020e-16-1.j, -1.46957616e-15-8.j])
numpy.power
Python Library Documentation: ufunc
power = <ufunc 'power'>
power(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
First array elements raised to powers from second array, element-wise.
Raise each base in `x1` to the positionally-corresponding power in
`x2`. `x1` and `x2` must be broadcastable to the same shape.
An integer type raised to a negative integer power will raise a
``ValueError``.
Negative values raised to a non-integral value will return ``nan``.
To get complex results, cast the input to complex, or specify the
``dtype`` to be ``complex`` (see the example below).
Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
float_power : power function that promotes integers to float
Examples
--------
>>> import numpy as np
Cube each element in an array.
>>> x1 = np.arange(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([ 0, 1, 8, 27, 64, 125])
Raise the bases to different exponents.
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([ 0., 1., 8., 27., 16., 5.])
The effect of broadcasting.
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0, 1, 8, 27, 16, 5],
[ 0, 1, 8, 27, 16, 5]])
The ``**`` operator can be used as a shorthand for ``np.power`` on
ndarrays.
>>> x2 = np.array([1, 2, 3, 3, 2, 1])
>>> x1 = np.arange(6)
>>> x1 ** x2
array([ 0, 1, 8, 27, 16, 5])
Negative values raised to a non-integral value will result in ``nan``
(and a warning will be generated).
>>> x3 = np.array([-1.0, -4.0])
>>> with np.errstate(invalid='ignore'):
... p = np.power(x3, 1.5)
...
>>> p
array([nan, nan])
To get complex results, give the argument ``dtype=complex``.
>>> np.power(x3, 1.5, dtype=complex)
array([-1.83697020e-16-1.j, -1.46957616e-15-8.j])
numpy.printoptions
Python Library Documentation: function printoptions in module numpy
printoptions(*args, **kwargs)
Context manager for setting print options.
Set print options for the scope of the `with` block, and restore the old
options at the end. See `set_printoptions` for the full description of
available options.
Examples
--------
>>> import numpy as np
>>> from numpy.testing import assert_equal
>>> with np.printoptions(precision=2):
... np.array([2.0]) / 3
array([0.67])
The `as`-clause of the `with`-statement gives the current print options:
>>> with np.printoptions(precision=2) as opts:
... assert_equal(opts, np.get_printoptions())
See Also
--------
set_printoptions, get_printoptions
numpy.prod
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
prod(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Return the product of array elements over a given axis.
Parameters
----------
a : array_like
Input data.
axis : None or int or tuple of ints, optional
Axis or axes along which a product is performed. The default,
axis=None, will calculate the product of all the elements in the
input array. If axis is negative it counts from the last to the
first axis.
.. versionadded:: 1.7.0
If axis is a tuple of ints, a product is performed on all of the
axes specified in the tuple instead of a single axis or all the
axes as before.
dtype : dtype, optional
The type of the returned array, as well as of the accumulator in
which the elements are multiplied. The dtype of `a` is used by
default unless `a` has an integer dtype of less precision than the
default platform integer. In that case, if `a` is signed then the
platform integer is used while if `a` is unsigned then an unsigned
integer of the same precision as the platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output, but the type of the output
values will be cast if necessary.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left in the
result as dimensions with size one. With this option, the result
will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `prod` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
initial : scalar, optional
The starting value for this product. See `~numpy.ufunc.reduce`
for details.
.. versionadded:: 1.15.0
where : array_like of bool, optional
Elements to include in the product. See `~numpy.ufunc.reduce`
for details.
.. versionadded:: 1.17.0
Returns
-------
product_along_axis : ndarray, see `dtype` parameter above.
An array shaped as `a` but with the specified axis removed.
Returns a reference to `out` if specified.
See Also
--------
ndarray.prod : equivalent method
:ref:`ufuncs-output-type`
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow. That means that, on a 32-bit platform:
>>> x = np.array([536870910, 536870910, 536870910, 536870910])
>>> np.prod(x)
16 # may vary
The product of an empty array is the neutral element 1:
>>> np.prod([])
1.0
Examples
--------
By default, calculate the product of all elements:
>>> import numpy as np
>>> np.prod([1.,2.])
2.0
Even when the input array is two-dimensional:
>>> a = np.array([[1., 2.], [3., 4.]])
>>> np.prod(a)
24.0
But we can also specify the axis over which to multiply:
>>> np.prod(a, axis=1)
array([ 2., 12.])
>>> np.prod(a, axis=0)
array([3., 8.])
Or select specific elements to include:
>>> np.prod([1., np.nan, 3.], where=[True, False, True])
3.0
If the type of `x` is unsigned, then the output type is
the unsigned platform integer:
>>> x = np.array([1, 2, 3], dtype=np.uint8)
>>> np.prod(x).dtype == np.uint
True
If `x` is of a signed integer type, then the output type
is the default platform integer:
>>> x = np.array([1, 2, 3], dtype=np.int8)
>>> np.prod(x).dtype == int
True
You can also start the product with a value other than one:
>>> np.prod([1, 2], initial=5)
10
numpy.promote_types
Python Library Documentation: built-in function promote_types in module numpy
promote_types(...)
promote_types(type1, type2)
Returns the data type with the smallest size and smallest scalar
kind to which both ``type1`` and ``type2`` may be safely cast.
The returned data type is always considered "canonical", this mainly
means that the promoted dtype will always be in native byte order.
This function is symmetric, but rarely associative.
Parameters
----------
type1 : dtype or dtype specifier
First data type.
type2 : dtype or dtype specifier
Second data type.
Returns
-------
out : dtype
The promoted data type.
Notes
-----
Please see `numpy.result_type` for additional information about promotion.
.. versionadded:: 1.6.0
Starting in NumPy 1.9, promote_types function now returns a valid string
length when given an integer or float dtype as one argument and a string
dtype as another argument. Previously it always returned the input string
dtype, even if it wasn't long enough to store the max integer/float value
converted to a string.
.. versionchanged:: 1.23.0
NumPy now supports promotion for more structured dtypes. It will now
remove unnecessary padding from a structure dtype and promote included
fields individually.
See Also
--------
result_type, dtype, can_cast
Examples
--------
>>> import numpy as np
>>> np.promote_types('f4', 'f8')
dtype('float64')
>>> np.promote_types('i8', 'f4')
dtype('float64')
>>> np.promote_types('>i8', '<c8')
dtype('complex128')
>>> np.promote_types('i4', 'S8')
dtype('S11')
An example of a non-associative case:
>>> p = np.promote_types
>>> p('S', p('i1', 'u1'))
dtype('S6')
>>> p(p('S', 'i1'), 'u1')
dtype('S4')
numpy.ptp
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
ptp(a, axis=None, out=None, keepdims=<no value>)
Range of values (maximum - minimum) along an axis.
The name of the function comes from the acronym for 'peak to peak'.
.. warning::
`ptp` preserves the data type of the array. This means the
return value for an input of signed integers with n bits
(e.g. `numpy.int8`, `numpy.int16`, etc) is also a signed integer
with n bits. In that case, peak-to-peak values greater than
``2**(n-1)-1`` will be returned as negative values. An example
with a work-around is shown below.
Parameters
----------
a : array_like
Input values.
axis : None or int or tuple of ints, optional
Axis along which to find the peaks. By default, flatten the
array. `axis` may be negative, in
which case it counts from the last to the first axis.
.. versionadded:: 1.15.0
If this is a tuple of ints, a reduction is performed on multiple
axes, instead of a single axis or all the axes as before.
out : array_like
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output,
but the type of the output values will be cast if necessary.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `ptp` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
Returns
-------
ptp : ndarray or scalar
The range of a given array - `scalar` if array is one-dimensional
or a new array holding the result along the given axis
Examples
--------
>>> import numpy as np
>>> x = np.array([[4, 9, 2, 10],
... [6, 9, 7, 12]])
>>> np.ptp(x, axis=1)
array([8, 6])
>>> np.ptp(x, axis=0)
array([2, 0, 5, 2])
>>> np.ptp(x)
10
This example shows that a negative value can be returned when
the input is an array of signed integers.
>>> y = np.array([[1, 127],
... [0, 127],
... [-1, 127],
... [-2, 127]], dtype=np.int8)
>>> np.ptp(y, axis=1)
array([ 126, 127, -128, -127], dtype=int8)
A work-around is to use the `view()` method to view the result as
unsigned integers with the same bit width:
>>> np.ptp(y, axis=1).view(np.uint8)
array([126, 127, 128, 129], dtype=uint8)
numpy.put
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
put(a, ind, v, mode='raise')
Replaces specified elements of an array with given values.
The indexing works on the flattened target array. `put` is roughly
equivalent to:
::
a.flat[ind] = v
Parameters
----------
a : ndarray
Target array.
ind : array_like
Target indices, interpreted as integers.
v : array_like
Values to place in `a` at target indices. If `v` is shorter than
`ind` it will be repeated as necessary.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
* 'raise' -- raise an error (default)
* 'wrap' -- wrap around
* 'clip' -- clip to the range
'clip' mode means that all indices that are too large are replaced
by the index that addresses the last element along that axis. Note
that this disables indexing with negative numbers. In 'raise' mode,
if an exception occurs the target array may still be modified.
See Also
--------
putmask, place
put_along_axis : Put elements by matching the array and the index arrays
Examples
--------
>>> import numpy as np
>>> a = np.arange(5)
>>> np.put(a, [0, 2], [-44, -55])
>>> a
array([-44, 1, -55, 3, 4])
>>> a = np.arange(5)
>>> np.put(a, 22, -5, mode='clip')
>>> a
array([ 0, 1, 2, 3, -5])
numpy.put_along_axis
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
put_along_axis(arr, indices, values, axis)
Put values into the destination array by matching 1d index and data slices.
This iterates over matching 1d slices oriented along the specified axis in
the index and data arrays, and uses the former to place values into the
latter. These slices can be different lengths.
Functions returning an index along an axis, like `argsort` and
`argpartition`, produce suitable indices for this function.
.. versionadded:: 1.15.0
Parameters
----------
arr : ndarray (Ni..., M, Nk...)
Destination array.
indices : ndarray (Ni..., J, Nk...)
Indices to change along each 1d slice of `arr`. This must match the
dimension of arr, but dimensions in Ni and Nj may be 1 to broadcast
against `arr`.
values : array_like (Ni..., J, Nk...)
values to insert at those indices. Its shape and dimension are
broadcast to match that of `indices`.
axis : int
The axis to take 1d slices along. If axis is None, the destination
array is treated as if a flattened 1d view had been created of it.
Notes
-----
This is equivalent to (but faster than) the following use of `ndindex` and
`s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices::
Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
J = indices.shape[axis] # Need not equal M
for ii in ndindex(Ni):
for kk in ndindex(Nk):
a_1d = a [ii + s_[:,] + kk]
indices_1d = indices[ii + s_[:,] + kk]
values_1d = values [ii + s_[:,] + kk]
for j in range(J):
a_1d[indices_1d[j]] = values_1d[j]
Equivalently, eliminating the inner loop, the last two lines would be::
a_1d[indices_1d] = values_1d
See Also
--------
take_along_axis :
Take values from the input array by matching 1d index and data slices
Examples
--------
>>> import numpy as np
For this sample array
>>> a = np.array([[10, 30, 20], [60, 40, 50]])
We can replace the maximum values with:
>>> ai = np.argmax(a, axis=1, keepdims=True)
>>> ai
array([[1],
[0]])
>>> np.put_along_axis(a, ai, 99, axis=1)
>>> a
array([[10, 99, 20],
[99, 40, 50]])
numpy.putmask
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
putmask(...)
putmask(a, mask, values)
Changes elements of an array based on conditional and input values.
Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.
If `values` is not the same size as `a` and `mask` then it will repeat.
This gives behavior different from ``a[mask] = values``.
Parameters
----------
a : ndarray
Target array.
mask : array_like
Boolean mask array. It has to be the same shape as `a`.
values : array_like
Values to put into `a` where `mask` is True. If `values` is smaller
than `a` it will be repeated.
See Also
--------
place, put, take, copyto
Examples
--------
>>> import numpy as np
>>> x = np.arange(6).reshape(2, 3)
>>> np.putmask(x, x>2, x**2)
>>> x
array([[ 0, 1, 2],
[ 9, 16, 25]])
If `values` is smaller than `a` it is repeated:
>>> x = np.arange(5)
>>> np.putmask(x, x>1, [-33, -44])
>>> x
array([ 0, 1, -33, -44, -33])
numpy.quantile
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
quantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, weights=None, interpolation=None)
Compute the q-th quantile of the data along the specified axis.
.. versionadded:: 1.15.0
Parameters
----------
a : array_like of real numbers
Input array or object that can be converted to an array.
q : array_like of float
Probability or sequence of probabilities of the quantiles to compute.
Values 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.
out : ndarray, 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_input : bool, 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.
method : str, optional
This parameter specifies the method to use for estimating the
quantile. There are many different methods, some unique to NumPy.
The recommended options, numbered as they appear in [1]_, are:
1. 'inverted_cdf'
2. 'averaged_inverted_cdf'
3. 'closest_observation'
4. 'interpolated_inverted_cdf'
5. 'hazen'
6. 'weibull'
7. 'linear' (default)
8. 'median_unbiased'
9. 'normal_unbiased'
The first three methods are discontinuous. For backward compatibility
with previous versions of NumPy, the following discontinuous variations
of the default 'linear' (7.) option are available:
* 'lower'
* 'higher',
* 'midpoint'
* 'nearest'
See Notes for details.
.. versionchanged:: 1.22.0
This argument was previously called "interpolation" and only
offered the "linear" default and last four options.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left in
the result as dimensions with size one. With this option, the
result will broadcast correctly against the original array `a`.
weights : array_like, optional
An array of weights associated with the values in `a`. Each value in
`a` contributes to the quantile according to its associated weight.
The weights array can either be 1-D (in which case its length must be
the size of `a` along the given axis) or of the same shape as `a`.
If `weights=None`, then all data in `a` are assumed to have a
weight equal to one.
Only `method="inverted_cdf"` supports weights.
See the notes for more details.
.. versionadded:: 2.0.0
interpolation : str, optional
Deprecated name for the method keyword argument.
.. deprecated:: 1.22.0
Returns
-------
quantile : scalar or ndarray
If `q` is a single probability and `axis=None`, then the result
is a scalar. If multiple probability levels 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
--------
mean
percentile : equivalent to quantile, but with q in the range [0, 100].
median : equivalent to ``quantile(..., 0.5)``
nanquantile
Notes
-----
Given a sample `a` from an underlying distribution, `quantile` provides a
nonparametric estimate of the inverse cumulative distribution function.
By default, this is done by interpolating between adjacent elements in
``y``, a sorted copy of `a`::
(1-g)*y[j] + g*y[j+1]
where the index ``j`` and coefficient ``g`` are the integral and
fractional components of ``q * (n-1)``, and ``n`` is the number of
elements in the sample.
This is a special case of Equation 1 of H&F [1]_. More generally,
- ``j = (q*n + m - 1) // 1``, and
- ``g = (q*n + m - 1) % 1``,
where ``m`` may be defined according to several different conventions.
The preferred convention may be selected using the ``method`` parameter:
=============================== =============== ===============
``method`` number in H&F ``m``
=============================== =============== ===============
``interpolated_inverted_cdf`` 4 ``0``
``hazen`` 5 ``1/2``
``weibull`` 6 ``q``
``linear`` (default) 7 ``1 - q``
``median_unbiased`` 8 ``q/3 + 1/3``
``normal_unbiased`` 9 ``q/4 + 3/8``
=============================== =============== ===============
Note that indices ``j`` and ``j + 1`` are clipped to the range ``0`` to
``n - 1`` when the results of the formula would be outside the allowed
range of non-negative indices. The ``- 1`` in the formulas for ``j`` and
``g`` accounts for Python's 0-based indexing.
The table above includes only the estimators from H&F that are continuous
functions of probability `q` (estimators 4-9). NumPy also provides the
three discontinuous estimators from H&F (estimators 1-3), where ``j`` is
defined as above, ``m`` is defined as follows, and ``g`` is a function
of the real-valued ``index = q*n + m - 1`` and ``j``.
1. ``inverted_cdf``: ``m = 0`` and ``g = int(index - j > 0)``
2. ``averaged_inverted_cdf``: ``m = 0`` and
``g = (1 + int(index - j > 0)) / 2``
3. ``closest_observation``: ``m = -1/2`` and
``g = 1 - int((index == j) & (j%2 == 1))``
For backward compatibility with previous versions of NumPy, `quantile`
provides four additional discontinuous estimators. Like
``method='linear'``, all have ``m = 1 - q`` so that ``j = q*(n-1) // 1``,
but ``g`` is defined as follows.
- ``lower``: ``g = 0``
- ``midpoint``: ``g = 0.5``
- ``higher``: ``g = 1``
- ``nearest``: ``g = (q*(n-1) % 1) > 0.5``
**Weighted quantiles:**
More formally, the quantile at probability level :math:`q` of a cumulative
distribution function :math:`F(y)=P(Y \leq y)` with probability measure
:math:`P` is defined as any number :math:`x` that fulfills the
*coverage conditions*
.. math:: P(Y < x) \leq q \quad\text{and}\quad P(Y \leq x) \geq q
with random variable :math:`Y\sim P`.
Sample quantiles, the result of `quantile`, provide nonparametric
estimation of the underlying population counterparts, represented by the
unknown :math:`F`, given a data vector `a` of length ``n``.
Some of the estimators above arise when one considers :math:`F` as the
empirical distribution function of the data, i.e.
:math:`F(y) = \frac{1}{n} \sum_i 1_{a_i \leq y}`.
Then, different methods correspond to different choices of :math:`x` that
fulfill the above coverage conditions. Methods that follow this approach
are ``inverted_cdf`` and ``averaged_inverted_cdf``.
For weighted quantiles, the coverage conditions still hold. The
empirical cumulative distribution is simply replaced by its weighted
version, i.e.
:math:`P(Y \leq t) = \frac{1}{\sum_i w_i} \sum_i w_i 1_{x_i \leq t}`.
Only ``method="inverted_cdf"`` supports weights.
Examples
--------
>>> import numpy as np
>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10, 7, 4],
[ 3, 2, 1]])
>>> np.quantile(a, 0.5)
3.5
>>> np.quantile(a, 0.5, axis=0)
array([6.5, 4.5, 2.5])
>>> np.quantile(a, 0.5, axis=1)
array([7., 2.])
>>> np.quantile(a, 0.5, axis=1, keepdims=True)
array([[7.],
[2.]])
>>> m = np.quantile(a, 0.5, axis=0)
>>> out = np.zeros_like(m)
>>> np.quantile(a, 0.5, axis=0, out=out)
array([6.5, 4.5, 2.5])
>>> m
array([6.5, 4.5, 2.5])
>>> b = a.copy()
>>> np.quantile(b, 0.5, axis=1, overwrite_input=True)
array([7., 2.])
>>> assert not np.all(a == b)
See also `numpy.percentile` for a visualization of most methods.
References
----------
.. [1] R. J. Hyndman and Y. Fan,
"Sample quantiles in statistical packages,"
The American Statistician, 50(4), pp. 361-365, 1996
numpy.r_
Python Library Documentation: RClass in module numpy.lib._index_tricks_impl object
class RClass(AxisConcatenator)
| Translates slice objects to concatenation along the first axis.
|
| This is a simple way to build up arrays quickly. There are two use cases.
|
| 1. If the index expression contains comma separated arrays, then stack
| them along their first axis.
| 2. If the index expression contains slice notation or scalars then create
| a 1-D array with a range indicated by the slice notation.
|
| If slice notation is used, the syntax ``start:stop:step`` is equivalent
| to ``np.arange(start, stop, step)`` inside of the brackets. However, if
| ``step`` is an imaginary number (i.e. 100j) then its integer portion is
| interpreted as a number-of-points desired and the start and stop are
| inclusive. In other words ``start:stop:stepj`` is interpreted as
| ``np.linspace(start, stop, step, endpoint=1)`` inside of the brackets.
| After expansion of slice notation, all comma separated sequences are
| concatenated together.
|
| Optional character strings placed as the first element of the index
| expression can be used to change the output. The strings 'r' or 'c' result
| in matrix output. If the result is 1-D and 'r' is specified a 1 x N (row)
| matrix is produced. If the result is 1-D and 'c' is specified, then a N x 1
| (column) matrix is produced. If the result is 2-D then both provide the
| same matrix result.
|
| A string integer specifies which axis to stack multiple comma separated
| arrays along. A string of two comma-separated integers allows indication
| of the minimum number of dimensions to force each entry into as the
| second integer (the axis to concatenate along is still the first integer).
|
| A string with three comma-separated integers allows specification of the
| axis to concatenate along, the minimum number of dimensions to force the
| entries to, and which axis should contain the start of the arrays which
| are less than the specified number of dimensions. In other words the third
| integer allows you to specify where the 1's should be placed in the shape
| of the arrays that have their shapes upgraded. By default, they are placed
| in the front of the shape tuple. The third argument allows you to specify
| where the start of the array should be instead. Thus, a third argument of
| '0' would place the 1's at the end of the array shape. Negative integers
| specify where in the new shape tuple the last dimension of upgraded arrays
| should be placed, so the default is '-1'.
|
| Parameters
| ----------
| Not a function, so takes no parameters
|
|
| Returns
| -------
| A concatenated ndarray or matrix.
|
| See Also
| --------
| concatenate : Join a sequence of arrays along an existing axis.
| c_ : Translates slice objects to concatenation along the second axis.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])]
| array([1, 2, 3, ..., 4, 5, 6])
| >>> np.r_[-1:1:6j, [0]*3, 5, 6]
| array([-1. , -0.6, -0.2, 0.2, 0.6, 1. , 0. , 0. , 0. , 5. , 6. ])
|
| String integers specify the axis to concatenate along or the minimum
| number of dimensions to force entries into.
|
| >>> a = np.array([[0, 1, 2], [3, 4, 5]])
| >>> np.r_['-1', a, a] # concatenate along last axis
| array([[0, 1, 2, 0, 1, 2],
| [3, 4, 5, 3, 4, 5]])
| >>> np.r_['0,2', [1,2,3], [4,5,6]] # concatenate along first axis, dim>=2
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> np.r_['0,2,0', [1,2,3], [4,5,6]]
| array([[1],
| [2],
| [3],
| [4],
| [5],
| [6]])
| >>> np.r_['1,2,0', [1,2,3], [4,5,6]]
| array([[1, 4],
| [2, 5],
| [3, 6]])
|
| Using 'r' or 'c' as a first string argument creates a matrix.
|
| >>> np.r_['r',[1,2,3], [4,5,6]]
| matrix([[1, 2, 3, 4, 5, 6]])
|
| Method resolution order:
| RClass
| AxisConcatenator
| builtins.object
|
| Methods defined here:
|
| __init__(self)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from AxisConcatenator:
|
| __getitem__(self, key)
|
| __len__(self)
|
| ----------------------------------------------------------------------
| Static methods inherited from AxisConcatenator:
|
| concatenate(...)
| concatenate(
| (a1, a2, ...),
| axis=0,
| out=None,
| dtype=None,
| casting="same_kind"
| )
|
| Join a sequence of arrays along an existing axis.
|
| Parameters
| ----------
| a1, a2, ... : sequence of array_like
| The arrays must have the same shape, except in the dimension
| corresponding to `axis` (the first, by default).
| axis : int, optional
| The axis along which the arrays will be joined. If axis is None,
| arrays are flattened before use. Default is 0.
| out : ndarray, optional
| If provided, the destination to place the result. The shape must be
| correct, matching that of what concatenate would have returned if no
| out argument were specified.
| dtype : str or dtype
| If provided, the destination array will have this dtype. Cannot be
| provided together with `out`.
|
| .. versionadded:: 1.20.0
|
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'same_kind'.
| For a description of the options, please see :term:`casting`.
|
| .. versionadded:: 1.20.0
|
| Returns
| -------
| res : ndarray
| The concatenated array.
|
| See Also
| --------
| ma.concatenate : Concatenate function that preserves input masks.
| array_split : Split an array into multiple sub-arrays of equal or
| near-equal size.
| split : Split array into a list of multiple sub-arrays of equal size.
| hsplit : Split array into multiple sub-arrays horizontally (column wise).
| vsplit : Split array into multiple sub-arrays vertically (row wise).
| dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
| stack : Stack a sequence of arrays along a new axis.
| block : Assemble arrays from blocks.
| hstack : Stack arrays in sequence horizontally (column wise).
| vstack : Stack arrays in sequence vertically (row wise).
| dstack : Stack arrays in sequence depth wise (along third dimension).
| column_stack : Stack 1-D arrays as columns into a 2-D array.
|
| Notes
| -----
| When one or more of the arrays to be concatenated is a MaskedArray,
| this function will return a MaskedArray object instead of an ndarray,
| but the input masks are *not* preserved. In cases where a MaskedArray
| is expected as input, use the ma.concatenate function from the masked
| array module instead.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> b = np.array([[5, 6]])
| >>> np.concatenate((a, b), axis=0)
| array([[1, 2],
| [3, 4],
| [5, 6]])
| >>> np.concatenate((a, b.T), axis=1)
| array([[1, 2, 5],
| [3, 4, 6]])
| >>> np.concatenate((a, b), axis=None)
| array([1, 2, 3, 4, 5, 6])
|
| This function will not preserve masking of MaskedArray inputs.
|
| >>> a = np.ma.arange(3)
| >>> a[1] = np.ma.masked
| >>> b = np.arange(2, 5)
| >>> a
| masked_array(data=[0, --, 2],
| mask=[False, True, False],
| fill_value=999999)
| >>> b
| array([2, 3, 4])
| >>> np.concatenate([a, b])
| masked_array(data=[0, 1, 2, 2, 3, 4],
| mask=False,
| fill_value=999999)
| >>> np.ma.concatenate([a, b])
| masked_array(data=[0, --, 2, 2, 3, 4],
| mask=[False, True, False, False, False, False],
| fill_value=999999)
|
| makemat = class matrix(ndarray)
| | makemat(data, dtype=None, copy=True)
| |
| | matrix(data, dtype=None, copy=True)
| |
| | Returns a matrix from an array-like object, or from a string of data.
| |
| | A matrix is a specialized 2-D array that retains its 2-D nature
| | through operations. It has certain special operators, such as ``*``
| | (matrix multiplication) and ``**`` (matrix power).
| |
| | .. note:: It is no longer recommended to use this class, even for linear
| | algebra. Instead use regular arrays. The class may be removed
| | in the future.
| |
| | Parameters
| | ----------
| | data : array_like or string
| | If `data` is a string, it is interpreted as a matrix with commas
| | or spaces separating columns, and semicolons separating rows.
| | dtype : data-type
| | Data-type of the output matrix.
| | copy : bool
| | If `data` is already an `ndarray`, then this flag determines
| | whether the data is copied (the default), or whether a view is
| | constructed.
| |
| | See Also
| | --------
| | array
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.matrix('1 2; 3 4')
| | >>> a
| | matrix([[1, 2],
| | [3, 4]])
| |
| | >>> np.matrix([[1, 2], [3, 4]])
| | matrix([[1, 2],
| | [3, 4]])
| |
| | Method resolution order:
| | matrix
| | ndarray
| | builtins.object
| |
| | Methods defined here:
| |
| | __array_finalize__(self, obj) from numpy.matrixlib.defmatrix.matrix
| | a.__array_finalize__(obj, /)
| |
| | Present so subclasses can call super. Does nothing.
| |
| | __getitem__(self, index) from numpy.matrixlib.defmatrix.matrix
| | Return self[key].
| |
| | __imul__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return self*=value.
| |
| | __ipow__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return self**=value.
| |
| | __mul__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return self*value.
| |
| | __pow__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return pow(self, value, mod).
| |
| | __rmul__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return value*self.
| |
| | __rpow__(self, other) from numpy.matrixlib.defmatrix.matrix
| | Return pow(value, self, mod).
| |
| | all(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Test whether all matrix elements along a given axis evaluate to True.
| |
| | Parameters
| | ----------
| | See `numpy.all` for complete descriptions
| |
| | See Also
| | --------
| | numpy.all
| |
| | Notes
| | -----
| | This is the same as `ndarray.all`, but it returns a `matrix` object.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> y = x[0]; y
| | matrix([[0, 1, 2, 3]])
| | >>> (x == y)
| | matrix([[ True, True, True, True],
| | [False, False, False, False],
| | [False, False, False, False]])
| | >>> (x == y).all()
| | False
| | >>> (x == y).all(0)
| | matrix([[False, False, False, False]])
| | >>> (x == y).all(1)
| | matrix([[ True],
| | [False],
| | [False]])
| |
| | any(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Test whether any array element along a given axis evaluates to True.
| |
| | Refer to `numpy.any` for full documentation.
| |
| | Parameters
| | ----------
| | axis : int, optional
| | Axis along which logical OR is performed
| | out : ndarray, optional
| | Output to existing array instead of creating new one, must have
| | same shape as expected output
| |
| | Returns
| | -------
| | any : bool, ndarray
| | Returns a single bool if `axis` is ``None``; otherwise,
| | returns `ndarray`
| |
| | argmax(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Indexes of the maximum values along an axis.
| |
| | Return the indexes of the first occurrences of the maximum values
| | along the specified axis. If axis is None, the index is for the
| | flattened matrix.
| |
| | Parameters
| | ----------
| | See `numpy.argmax` for complete descriptions
| |
| | See Also
| | --------
| | numpy.argmax
| |
| | Notes
| | -----
| | This is the same as `ndarray.argmax`, but returns a `matrix` object
| | where `ndarray.argmax` would return an `ndarray`.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.argmax()
| | 11
| | >>> x.argmax(0)
| | matrix([[2, 2, 2, 2]])
| | >>> x.argmax(1)
| | matrix([[3],
| | [3],
| | [3]])
| |
| | argmin(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Indexes of the minimum values along an axis.
| |
| | Return the indexes of the first occurrences of the minimum values
| | along the specified axis. If axis is None, the index is for the
| | flattened matrix.
| |
| | Parameters
| | ----------
| | See `numpy.argmin` for complete descriptions.
| |
| | See Also
| | --------
| | numpy.argmin
| |
| | Notes
| | -----
| | This is the same as `ndarray.argmin`, but returns a `matrix` object
| | where `ndarray.argmin` would return an `ndarray`.
| |
| | Examples
| | --------
| | >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, -1, -2, -3],
| | [ -4, -5, -6, -7],
| | [ -8, -9, -10, -11]])
| | >>> x.argmin()
| | 11
| | >>> x.argmin(0)
| | matrix([[2, 2, 2, 2]])
| | >>> x.argmin(1)
| | matrix([[3],
| | [3],
| | [3]])
| |
| | flatten(self, order='C') from numpy.matrixlib.defmatrix.matrix
| | Return a flattened copy of the matrix.
| |
| | All `N` elements of the matrix are placed into a single row.
| |
| | Parameters
| | ----------
| | order : {'C', 'F', 'A', 'K'}, optional
| | 'C' means to flatten in row-major (C-style) order. 'F' means to
| | flatten in column-major (Fortran-style) order. 'A' means to
| | flatten in column-major order if `m` is Fortran *contiguous* in
| | memory, row-major order otherwise. 'K' means to flatten `m` in
| | the order the elements occur in memory. The default is 'C'.
| |
| | Returns
| | -------
| | y : matrix
| | A copy of the matrix, flattened to a `(1, N)` matrix where `N`
| | is the number of elements in the original matrix.
| |
| | See Also
| | --------
| | ravel : Return a flattened array.
| | flat : A 1-D flat iterator over the matrix.
| |
| | Examples
| | --------
| | >>> m = np.matrix([[1,2], [3,4]])
| | >>> m.flatten()
| | matrix([[1, 2, 3, 4]])
| | >>> m.flatten('F')
| | matrix([[1, 3, 2, 4]])
| |
| | getA = A(self) from numpy.matrixlib.defmatrix.matrix
| | Return `self` as an `ndarray` object.
| |
| | Equivalent to ``np.asarray(self)``.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : ndarray
| | `self` as an `ndarray`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.getA()
| | array([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| |
| | getA1 = A1(self) from numpy.matrixlib.defmatrix.matrix
| | Return `self` as a flattened `ndarray`.
| |
| | Equivalent to ``np.asarray(x).ravel()``
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : ndarray
| | `self`, 1-D, as an `ndarray`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.getA1()
| | array([ 0, 1, 2, ..., 9, 10, 11])
| |
| | getH = H(self) from numpy.matrixlib.defmatrix.matrix
| | Returns the (complex) conjugate transpose of `self`.
| |
| | Equivalent to ``np.transpose(self)`` if `self` is real-valued.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | complex conjugate transpose of `self`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4)))
| | >>> z = x - 1j*x; z
| | matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
| | [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
| | [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
| | >>> z.getH()
| | matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
| | [ 1. +1.j, 5. +5.j, 9. +9.j],
| | [ 2. +2.j, 6. +6.j, 10.+10.j],
| | [ 3. +3.j, 7. +7.j, 11.+11.j]])
| |
| | getI = I(self) from numpy.matrixlib.defmatrix.matrix
| | Returns the (multiplicative) inverse of invertible `self`.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | If `self` is non-singular, `ret` is such that ``ret * self`` ==
| | ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
| | ``True``.
| |
| | Raises
| | ------
| | numpy.linalg.LinAlgError: Singular matrix
| | If `self` is singular.
| |
| | See Also
| | --------
| | linalg.inv
| |
| | Examples
| | --------
| | >>> m = np.matrix('[1, 2; 3, 4]'); m
| | matrix([[1, 2],
| | [3, 4]])
| | >>> m.getI()
| | matrix([[-2. , 1. ],
| | [ 1.5, -0.5]])
| | >>> m.getI() * m
| | matrix([[ 1., 0.], # may vary
| | [ 0., 1.]])
| |
| | getT = T(self) from numpy.matrixlib.defmatrix.matrix
| | Returns the transpose of the matrix.
| |
| | Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | The (non-conjugated) transpose of the matrix.
| |
| | See Also
| | --------
| | transpose, getH
| |
| | Examples
| | --------
| | >>> m = np.matrix('[1, 2; 3, 4]')
| | >>> m
| | matrix([[1, 2],
| | [3, 4]])
| | >>> m.getT()
| | matrix([[1, 3],
| | [2, 4]])
| |
| | max(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Return the maximum value along an axis.
| |
| | Parameters
| | ----------
| | See `amax` for complete descriptions
| |
| | See Also
| | --------
| | amax, ndarray.max
| |
| | Notes
| | -----
| | This is the same as `ndarray.max`, but returns a `matrix` object
| | where `ndarray.max` would return an ndarray.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.max()
| | 11
| | >>> x.max(0)
| | matrix([[ 8, 9, 10, 11]])
| | >>> x.max(1)
| | matrix([[ 3],
| | [ 7],
| | [11]])
| |
| | mean(self, axis=None, dtype=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Returns the average of the matrix elements along the given axis.
| |
| | Refer to `numpy.mean` for full documentation.
| |
| | See Also
| | --------
| | numpy.mean
| |
| | Notes
| | -----
| | Same as `ndarray.mean` except that, where that returns an `ndarray`,
| | this returns a `matrix` object.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3, 4)))
| | >>> x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.mean()
| | 5.5
| | >>> x.mean(0)
| | matrix([[4., 5., 6., 7.]])
| | >>> x.mean(1)
| | matrix([[ 1.5],
| | [ 5.5],
| | [ 9.5]])
| |
| | min(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Return the minimum value along an axis.
| |
| | Parameters
| | ----------
| | See `amin` for complete descriptions.
| |
| | See Also
| | --------
| | amin, ndarray.min
| |
| | Notes
| | -----
| | This is the same as `ndarray.min`, but returns a `matrix` object
| | where `ndarray.min` would return an ndarray.
| |
| | Examples
| | --------
| | >>> x = -np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, -1, -2, -3],
| | [ -4, -5, -6, -7],
| | [ -8, -9, -10, -11]])
| | >>> x.min()
| | -11
| | >>> x.min(0)
| | matrix([[ -8, -9, -10, -11]])
| | >>> x.min(1)
| | matrix([[ -3],
| | [ -7],
| | [-11]])
| |
| | prod(self, axis=None, dtype=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Return the product of the array elements over the given axis.
| |
| | Refer to `prod` for full documentation.
| |
| | See Also
| | --------
| | prod, ndarray.prod
| |
| | Notes
| | -----
| | Same as `ndarray.prod`, except, where that returns an `ndarray`, this
| | returns a `matrix` object instead.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.prod()
| | 0
| | >>> x.prod(0)
| | matrix([[ 0, 45, 120, 231]])
| | >>> x.prod(1)
| | matrix([[ 0],
| | [ 840],
| | [7920]])
| |
| | ptp(self, axis=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Peak-to-peak (maximum - minimum) value along the given axis.
| |
| | Refer to `numpy.ptp` for full documentation.
| |
| | See Also
| | --------
| | numpy.ptp
| |
| | Notes
| | -----
| | Same as `ndarray.ptp`, except, where that would return an `ndarray` object,
| | this returns a `matrix` object.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.ptp()
| | 11
| | >>> x.ptp(0)
| | matrix([[8, 8, 8, 8]])
| | >>> x.ptp(1)
| | matrix([[3],
| | [3],
| | [3]])
| |
| | ravel(self, order='C') from numpy.matrixlib.defmatrix.matrix
| | Return a flattened matrix.
| |
| | Refer to `numpy.ravel` for more documentation.
| |
| | Parameters
| | ----------
| | order : {'C', 'F', 'A', 'K'}, optional
| | The elements of `m` are read using this index order. 'C' means to
| | index the elements in C-like order, with the last axis index
| | changing fastest, back to the first axis index changing slowest.
| | 'F' means to index the elements in Fortran-like index order, with
| | the first index changing fastest, and the last index changing
| | slowest. Note that the 'C' and 'F' options take no account of the
| | memory layout of the underlying array, and only refer to the order
| | of axis indexing. 'A' means to read the elements in Fortran-like
| | index order if `m` is Fortran *contiguous* in memory, C-like order
| | otherwise. 'K' means to read the elements in the order they occur
| | in memory, except for reversing the data when strides are negative.
| | By default, 'C' index order is used.
| |
| | Returns
| | -------
| | ret : matrix
| | Return the matrix flattened to shape `(1, N)` where `N`
| | is the number of elements in the original matrix.
| | A copy is made only if necessary.
| |
| | See Also
| | --------
| | matrix.flatten : returns a similar output matrix but always a copy
| | matrix.flat : a flat iterator on the array.
| | numpy.ravel : related function which returns an ndarray
| |
| | squeeze(self, axis=None) from numpy.matrixlib.defmatrix.matrix
| | Return a possibly reshaped matrix.
| |
| | Refer to `numpy.squeeze` for more documentation.
| |
| | Parameters
| | ----------
| | axis : None or int or tuple of ints, optional
| | Selects a subset of the axes of length one in the shape.
| | If an axis is selected with shape entry greater than one,
| | an error is raised.
| |
| | Returns
| | -------
| | squeezed : matrix
| | The matrix, but as a (1, N) matrix if it had shape (N, 1).
| |
| | See Also
| | --------
| | numpy.squeeze : related function
| |
| | Notes
| | -----
| | If `m` has a single column then that column is returned
| | as the single row of a matrix. Otherwise `m` is returned.
| | The returned matrix is always either `m` itself or a view into `m`.
| | Supplying an axis keyword argument will not affect the returned matrix
| | but it may cause an error to be raised.
| |
| | Examples
| | --------
| | >>> c = np.matrix([[1], [2]])
| | >>> c
| | matrix([[1],
| | [2]])
| | >>> c.squeeze()
| | matrix([[1, 2]])
| | >>> r = c.T
| | >>> r
| | matrix([[1, 2]])
| | >>> r.squeeze()
| | matrix([[1, 2]])
| | >>> m = np.matrix([[1, 2], [3, 4]])
| | >>> m.squeeze()
| | matrix([[1, 2],
| | [3, 4]])
| |
| | std(self, axis=None, dtype=None, out=None, ddof=0) from numpy.matrixlib.defmatrix.matrix
| | Return the standard deviation of the array elements along the given axis.
| |
| | Refer to `numpy.std` for full documentation.
| |
| | See Also
| | --------
| | numpy.std
| |
| | Notes
| | -----
| | This is the same as `ndarray.std`, except that where an `ndarray` would
| | be returned, a `matrix` object is returned instead.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3, 4)))
| | >>> x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.std()
| | 3.4520525295346629 # may vary
| | >>> x.std(0)
| | matrix([[ 3.26598632, 3.26598632, 3.26598632, 3.26598632]]) # may vary
| | >>> x.std(1)
| | matrix([[ 1.11803399],
| | [ 1.11803399],
| | [ 1.11803399]])
| |
| | sum(self, axis=None, dtype=None, out=None) from numpy.matrixlib.defmatrix.matrix
| | Returns the sum of the matrix elements, along the given axis.
| |
| | Refer to `numpy.sum` for full documentation.
| |
| | See Also
| | --------
| | numpy.sum
| |
| | Notes
| | -----
| | This is the same as `ndarray.sum`, except that where an `ndarray` would
| | be returned, a `matrix` object is returned instead.
| |
| | Examples
| | --------
| | >>> x = np.matrix([[1, 2], [4, 3]])
| | >>> x.sum()
| | 10
| | >>> x.sum(axis=1)
| | matrix([[3],
| | [7]])
| | >>> x.sum(axis=1, dtype='float')
| | matrix([[3.],
| | [7.]])
| | >>> out = np.zeros((2, 1), dtype='float')
| | >>> x.sum(axis=1, dtype='float', out=np.asmatrix(out))
| | matrix([[3.],
| | [7.]])
| |
| | tolist(self) from numpy.matrixlib.defmatrix.matrix
| | Return the matrix as a (possibly nested) list.
| |
| | See `ndarray.tolist` for full documentation.
| |
| | See Also
| | --------
| | ndarray.tolist
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.tolist()
| | [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
| |
| | var(self, axis=None, dtype=None, out=None, ddof=0) from numpy.matrixlib.defmatrix.matrix
| | Returns the variance of the matrix elements, along the given axis.
| |
| | Refer to `numpy.var` for full documentation.
| |
| | See Also
| | --------
| | numpy.var
| |
| | Notes
| | -----
| | This is the same as `ndarray.var`, except that where an `ndarray` would
| | be returned, a `matrix` object is returned instead.
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3, 4)))
| | >>> x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.var()
| | 11.916666666666666
| | >>> x.var(0)
| | matrix([[ 10.66666667, 10.66666667, 10.66666667, 10.66666667]]) # may vary
| | >>> x.var(1)
| | matrix([[1.25],
| | [1.25],
| | [1.25]])
| |
| | ----------------------------------------------------------------------
| | Static methods defined here:
| |
| | __new__(subtype, data, dtype=None, copy=True) from numpy.matrixlib.defmatrix.matrix
| | Create and return a new object. See help(type) for accurate signature.
| |
| | ----------------------------------------------------------------------
| | Readonly properties defined here:
| |
| | A
| | Return `self` as an `ndarray` object.
| |
| | Equivalent to ``np.asarray(self)``.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : ndarray
| | `self` as an `ndarray`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.getA()
| | array([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| |
| | A1
| | Return `self` as a flattened `ndarray`.
| |
| | Equivalent to ``np.asarray(x).ravel()``
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : ndarray
| | `self`, 1-D, as an `ndarray`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4))); x
| | matrix([[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]])
| | >>> x.getA1()
| | array([ 0, 1, 2, ..., 9, 10, 11])
| |
| | H
| | Returns the (complex) conjugate transpose of `self`.
| |
| | Equivalent to ``np.transpose(self)`` if `self` is real-valued.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | complex conjugate transpose of `self`
| |
| | Examples
| | --------
| | >>> x = np.matrix(np.arange(12).reshape((3,4)))
| | >>> z = x - 1j*x; z
| | matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
| | [ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
| | [ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
| | >>> z.getH()
| | matrix([[ 0. -0.j, 4. +4.j, 8. +8.j],
| | [ 1. +1.j, 5. +5.j, 9. +9.j],
| | [ 2. +2.j, 6. +6.j, 10.+10.j],
| | [ 3. +3.j, 7. +7.j, 11.+11.j]])
| |
| | I
| | Returns the (multiplicative) inverse of invertible `self`.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | If `self` is non-singular, `ret` is such that ``ret * self`` ==
| | ``self * ret`` == ``np.matrix(np.eye(self[0,:].size))`` all return
| | ``True``.
| |
| | Raises
| | ------
| | numpy.linalg.LinAlgError: Singular matrix
| | If `self` is singular.
| |
| | See Also
| | --------
| | linalg.inv
| |
| | Examples
| | --------
| | >>> m = np.matrix('[1, 2; 3, 4]'); m
| | matrix([[1, 2],
| | [3, 4]])
| | >>> m.getI()
| | matrix([[-2. , 1. ],
| | [ 1.5, -0.5]])
| | >>> m.getI() * m
| | matrix([[ 1., 0.], # may vary
| | [ 0., 1.]])
| |
| | T
| | Returns the transpose of the matrix.
| |
| | Does *not* conjugate! For the complex conjugate transpose, use ``.H``.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | ret : matrix object
| | The (non-conjugated) transpose of the matrix.
| |
| | See Also
| | --------
| | transpose, getH
| |
| | Examples
| | --------
| | >>> m = np.matrix('[1, 2; 3, 4]')
| | >>> m
| | matrix([[1, 2],
| | [3, 4]])
| | >>> m.getT()
| | matrix([[1, 3],
| | [2, 4]])
| |
| | ----------------------------------------------------------------------
| | Data descriptors defined here:
| |
| | __dict__
| | dictionary for instance variables
| |
| | ----------------------------------------------------------------------
| | Data and other attributes defined here:
| |
| | __annotations__ = {}
| |
| | __array_priority__ = 10.0
| |
| | ----------------------------------------------------------------------
| | Methods inherited from ndarray:
| |
| | __abs__(self, /)
| | abs(self)
| |
| | __add__(self, value, /)
| | Return self+value.
| |
| | __and__(self, value, /)
| | Return self&value.
| |
| | __array__(...)
| | a.__array__([dtype], *, copy=None)
| |
| | For ``dtype`` parameter it returns a new reference to self if
| | ``dtype`` is not given or it matches array's data type.
| | A new array of provided data type is returned if ``dtype``
| | is different from the current data type of the array.
| | For ``copy`` parameter it returns a new reference to self if
| | ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| | parameter. The method returns a new array for ``copy=True``, regardless of
| | ``dtype`` parameter.
| |
| | A more detailed explanation of the ``__array__`` interface
| | can be found in :ref:`dunder_array.interface`.
| |
| | __array_function__(...)
| |
| | __array_namespace__(...)
| |
| | __array_ufunc__(...)
| |
| | __array_wrap__(...)
| | a.__array_wrap__(array[, context], /)
| |
| | Returns a view of `array` with the same type as self.
| |
| | __bool__(self, /)
| | True if self else False
| |
| | __buffer__(self, flags, /)
| | Return a buffer object that exposes the underlying memory of the object.
| |
| | __complex__(...)
| |
| | __contains__(self, key, /)
| | Return bool(key in self).
| |
| | __copy__(...)
| | a.__copy__()
| |
| | Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
| |
| | Equivalent to ``a.copy(order='K')``.
| |
| | __deepcopy__(...)
| | a.__deepcopy__(memo, /)
| |
| | Used if :func:`copy.deepcopy` is called on an array.
| |
| | __delitem__(self, key, /)
| | Delete self[key].
| |
| | __divmod__(self, value, /)
| | Return divmod(self, value).
| |
| | __dlpack__(...)
| | a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
| |
| | DLPack Protocol: Part of the Array API.
| |
| | __dlpack_device__(...)
| | a.__dlpack_device__()
| |
| | DLPack Protocol: Part of the Array API.
| |
| | __eq__(self, value, /)
| | Return self==value.
| |
| | __float__(self, /)
| | float(self)
| |
| | __floordiv__(self, value, /)
| | Return self//value.
| |
| | __format__(...)
| | Default object formatter.
| |
| | Return str(self) if format_spec is empty. Raise TypeError otherwise.
| |
| | __ge__(self, value, /)
| | Return self>=value.
| |
| | __gt__(self, value, /)
| | Return self>value.
| |
| | __iadd__(self, value, /)
| | Return self+=value.
| |
| | __iand__(self, value, /)
| | Return self&=value.
| |
| | __ifloordiv__(self, value, /)
| | Return self//=value.
| |
| | __ilshift__(self, value, /)
| | Return self<<=value.
| |
| | __imatmul__(self, value, /)
| | Return self@=value.
| |
| | __imod__(self, value, /)
| | Return self%=value.
| |
| | __index__(self, /)
| | Return self converted to an integer, if self is suitable for use as an index into a list.
| |
| | __int__(self, /)
| | int(self)
| |
| | __invert__(self, /)
| | ~self
| |
| | __ior__(self, value, /)
| | Return self|=value.
| |
| | __irshift__(self, value, /)
| | Return self>>=value.
| |
| | __isub__(self, value, /)
| | Return self-=value.
| |
| | __iter__(self, /)
| | Implement iter(self).
| |
| | __itruediv__(self, value, /)
| | Return self/=value.
| |
| | __ixor__(self, value, /)
| | Return self^=value.
| |
| | __le__(self, value, /)
| | Return self<=value.
| |
| | __len__(self, /)
| | Return len(self).
| |
| | __lshift__(self, value, /)
| | Return self<<value.
| |
| | __lt__(self, value, /)
| | Return self<value.
| |
| | __matmul__(self, value, /)
| | Return self@value.
| |
| | __mod__(self, value, /)
| | Return self%value.
| |
| | __ne__(self, value, /)
| | Return self!=value.
| |
| | __neg__(self, /)
| | -self
| |
| | __or__(self, value, /)
| | Return self|value.
| |
| | __pos__(self, /)
| | +self
| |
| | __radd__(self, value, /)
| | Return value+self.
| |
| | __rand__(self, value, /)
| | Return value&self.
| |
| | __rdivmod__(self, value, /)
| | Return divmod(value, self).
| |
| | __reduce__(...)
| | a.__reduce__()
| |
| | For pickling.
| |
| | __reduce_ex__(...)
| | Helper for pickle.
| |
| | __repr__(self, /)
| | Return repr(self).
| |
| | __rfloordiv__(self, value, /)
| | Return value//self.
| |
| | __rlshift__(self, value, /)
| | Return value<<self.
| |
| | __rmatmul__(self, value, /)
| | Return value@self.
| |
| | __rmod__(self, value, /)
| | Return value%self.
| |
| | __ror__(self, value, /)
| | Return value|self.
| |
| | __rrshift__(self, value, /)
| | Return value>>self.
| |
| | __rshift__(self, value, /)
| | Return self>>value.
| |
| | __rsub__(self, value, /)
| | Return value-self.
| |
| | __rtruediv__(self, value, /)
| | Return value/self.
| |
| | __rxor__(self, value, /)
| | Return value^self.
| |
| | __setitem__(self, key, value, /)
| | Set self[key] to value.
| |
| | __setstate__(...)
| | a.__setstate__(state, /)
| |
| | For unpickling.
| |
| | The `state` argument must be a sequence that contains the following
| | elements:
| |
| | Parameters
| | ----------
| | version : int
| | optional pickle version. If omitted defaults to 0.
| | shape : tuple
| | dtype : data-type
| | isFortran : bool
| | rawdata : string or list
| | a binary string with the data (or a list if 'a' is an object array)
| |
| | __sizeof__(...)
| | Size of object in memory, in bytes.
| |
| | __str__(self, /)
| | Return str(self).
| |
| | __sub__(self, value, /)
| | Return self-value.
| |
| | __truediv__(self, value, /)
| | Return self/value.
| |
| | __xor__(self, value, /)
| | Return self^value.
| |
| | argpartition(...)
| | a.argpartition(kth, axis=-1, kind='introselect', order=None)
| |
| | Returns the indices that would partition this array.
| |
| | Refer to `numpy.argpartition` for full documentation.
| |
| | .. versionadded:: 1.8.0
| |
| | See Also
| | --------
| | numpy.argpartition : equivalent function
| |
| | argsort(...)
| | a.argsort(axis=-1, kind=None, order=None)
| |
| | Returns the indices that would sort this array.
| |
| | Refer to `numpy.argsort` for full documentation.
| |
| | See Also
| | --------
| | numpy.argsort : equivalent function
| |
| | astype(...)
| | a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
| |
| | Copy of the array, cast to a specified type.
| |
| | Parameters
| | ----------
| | dtype : str or dtype
| | Typecode or data-type to which the array is cast.
| | order : {'C', 'F', 'A', 'K'}, optional
| | Controls the memory layout order of the result.
| | '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.
| | Default is 'K'.
| | casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| | Controls what kind of data casting may occur. Defaults to 'unsafe'
| | for backwards compatibility.
| |
| | * '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.
| | subok : bool, optional
| | If True, then sub-classes will be passed-through (default), otherwise
| | the returned array will be forced to be a base-class array.
| | copy : bool, optional
| | By default, astype always returns a newly allocated array. If this
| | is set to false, and the `dtype`, `order`, and `subok`
| | requirements are satisfied, the input array is returned instead
| | of a copy.
| |
| | Returns
| | -------
| | arr_t : ndarray
| | Unless `copy` is False and the other conditions for returning the input
| | array are satisfied (see description for `copy` input parameter), `arr_t`
| | is a new array of the same shape as the input array, with dtype, order
| | given by `dtype`, `order`.
| |
| | Notes
| | -----
| | .. versionchanged:: 1.17.0
| | Casting between a simple data type and a structured one is possible only
| | for "unsafe" casting. Casting to multiple fields is allowed, but
| | casting from multiple fields is not.
| |
| | .. versionchanged:: 1.9.0
| | Casting from numeric to string types in 'safe' casting mode requires
| | that the string dtype length is long enough to store the max
| | integer/float value converted.
| |
| | Raises
| | ------
| | ComplexWarning
| | When casting from complex to float or int. To avoid this,
| | one should use ``a.real.astype(t)``.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([1, 2, 2.5])
| | >>> x
| | array([1. , 2. , 2.5])
| |
| | >>> x.astype(int)
| | array([1, 2, 2])
| |
| | byteswap(...)
| | a.byteswap(inplace=False)
| |
| | Swap the bytes of the array elements
| |
| | Toggle between low-endian and big-endian data representation by
| | returning a byteswapped array, optionally swapped in-place.
| | Arrays of byte-strings are not swapped. The real and imaginary
| | parts of a complex number are swapped individually.
| |
| | Parameters
| | ----------
| | inplace : bool, optional
| | If ``True``, swap bytes in-place, default is ``False``.
| |
| | Returns
| | -------
| | out : ndarray
| | The byteswapped array. If `inplace` is ``True``, this is
| | a view to self.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> A = np.array([1, 256, 8755], dtype=np.int16)
| | >>> list(map(hex, A))
| | ['0x1', '0x100', '0x2233']
| | >>> A.byteswap(inplace=True)
| | array([ 256, 1, 13090], dtype=int16)
| | >>> list(map(hex, A))
| | ['0x100', '0x1', '0x3322']
| |
| | Arrays of byte-strings are not swapped
| |
| | >>> A = np.array([b'ceg', b'fac'])
| | >>> A.byteswap()
| | array([b'ceg', b'fac'], dtype='|S3')
| |
| | ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| | the same values but different representation in memory
| |
| | >>> A = np.array([1, 2, 3])
| | >>> A.view(np.uint8)
| | array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| | 0, 0], dtype=uint8)
| | >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| | array([1, 2, 3])
| | >>> A.view(np.uint8)
| | array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| | 0, 3], dtype=uint8)
| |
| | choose(...)
| | a.choose(choices, out=None, mode='raise')
| |
| | Use an index array to construct a new array from a set of choices.
| |
| | Refer to `numpy.choose` for full documentation.
| |
| | See Also
| | --------
| | numpy.choose : equivalent function
| |
| | clip(...)
| | a.clip(min=None, max=None, out=None, **kwargs)
| |
| | Return an array whose values are limited to ``[min, max]``.
| | One of max or min must be given.
| |
| | Refer to `numpy.clip` for full documentation.
| |
| | See Also
| | --------
| | numpy.clip : equivalent function
| |
| | compress(...)
| | a.compress(condition, axis=None, out=None)
| |
| | Return selected slices of this array along given axis.
| |
| | Refer to `numpy.compress` for full documentation.
| |
| | See Also
| | --------
| | numpy.compress : equivalent function
| |
| | conj(...)
| | a.conj()
| |
| | Complex-conjugate all elements.
| |
| | Refer to `numpy.conjugate` for full documentation.
| |
| | See Also
| | --------
| | numpy.conjugate : equivalent function
| |
| | conjugate(...)
| | a.conjugate()
| |
| | Return the complex conjugate, element-wise.
| |
| | Refer to `numpy.conjugate` for full documentation.
| |
| | See Also
| | --------
| | numpy.conjugate : equivalent function
| |
| | copy(...)
| | a.copy(order='C')
| |
| | Return a copy of the array.
| |
| | Parameters
| | ----------
| | order : {'C', 'F', 'A', 'K'}, optional
| | Controls the memory layout of the copy. 'C' means C-order,
| | 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| | 'C' otherwise. 'K' means match the layout of `a` as closely
| | as possible. (Note that this function and :func:`numpy.copy` are very
| | similar but have different default values for their order=
| | arguments, and this function always passes sub-classes through.)
| |
| | See also
| | --------
| | numpy.copy : Similar function with different default behavior
| | numpy.copyto
| |
| | Notes
| | -----
| | This function is the preferred method for creating an array copy. The
| | function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| | and will not pass sub-classes through by default.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([[1,2,3],[4,5,6]], order='F')
| |
| | >>> y = x.copy()
| |
| | >>> x.fill(0)
| |
| | >>> x
| | array([[0, 0, 0],
| | [0, 0, 0]])
| |
| | >>> y
| | array([[1, 2, 3],
| | [4, 5, 6]])
| |
| | >>> y.flags['C_CONTIGUOUS']
| | True
| |
| | For arrays containing Python objects (e.g. dtype=object),
| | the copy is a shallow one. The new array will contain the
| | same object which may lead to surprises if that object can
| | be modified (is mutable):
| |
| | >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| | >>> b = a.copy()
| | >>> b[2][0] = 10
| | >>> a
| | array([1, 'm', list([10, 3, 4])], dtype=object)
| |
| | To ensure all elements within an ``object`` array are copied,
| | use `copy.deepcopy`:
| |
| | >>> import copy
| | >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| | >>> c = copy.deepcopy(a)
| | >>> c[2][0] = 10
| | >>> c
| | array([1, 'm', list([10, 3, 4])], dtype=object)
| | >>> a
| | array([1, 'm', list([2, 3, 4])], dtype=object)
| |
| | cumprod(...)
| | a.cumprod(axis=None, dtype=None, out=None)
| |
| | Return the cumulative product of the elements along the given axis.
| |
| | Refer to `numpy.cumprod` for full documentation.
| |
| | See Also
| | --------
| | numpy.cumprod : equivalent function
| |
| | cumsum(...)
| | a.cumsum(axis=None, dtype=None, out=None)
| |
| | Return the cumulative sum of the elements along the given axis.
| |
| | Refer to `numpy.cumsum` for full documentation.
| |
| | See Also
| | --------
| | numpy.cumsum : equivalent function
| |
| | diagonal(...)
| | a.diagonal(offset=0, axis1=0, axis2=1)
| |
| | Return specified diagonals. In NumPy 1.9 the returned array is a
| | read-only view instead of a copy as in previous NumPy versions. In
| | a future version the read-only restriction will be removed.
| |
| | Refer to :func:`numpy.diagonal` for full documentation.
| |
| | See Also
| | --------
| | numpy.diagonal : equivalent function
| |
| | dot(...)
| |
| | dump(...)
| | a.dump(file)
| |
| | Dump a pickle of the array to the specified file.
| | The array can be read back with pickle.load or numpy.load.
| |
| | Parameters
| | ----------
| | file : str or Path
| | A string naming the dump file.
| |
| | .. versionchanged:: 1.17.0
| | `pathlib.Path` objects are now accepted.
| |
| | dumps(...)
| | a.dumps()
| |
| | Returns the pickle of the array as a string.
| | pickle.loads will convert the string back to an array.
| |
| | Parameters
| | ----------
| | None
| |
| | fill(...)
| | a.fill(value)
| |
| | Fill the array with a scalar value.
| |
| | Parameters
| | ----------
| | value : scalar
| | All elements of `a` will be assigned this value.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.array([1, 2])
| | >>> a.fill(0)
| | >>> a
| | array([0, 0])
| | >>> a = np.empty(2)
| | >>> a.fill(1)
| | >>> a
| | array([1., 1.])
| |
| | Fill expects a scalar value and always behaves the same as assigning
| | to a single array element. The following is a rare example where this
| | distinction is important:
| |
| | >>> a = np.array([None, None], dtype=object)
| | >>> a[0] = np.array(3)
| | >>> a
| | array([array(3), None], dtype=object)
| | >>> a.fill(np.array(3))
| | >>> a
| | array([array(3), array(3)], dtype=object)
| |
| | Where other forms of assignments will unpack the array being assigned:
| |
| | >>> a[...] = np.array(3)
| | >>> a
| | array([3, 3], dtype=object)
| |
| | getfield(...)
| | a.getfield(dtype, offset=0)
| |
| | Returns a field of the given array as a certain type.
| |
| | A field is a view of the array data with a given data-type. The values in
| | the view are determined by the given type and the offset into the current
| | array in bytes. The offset needs to be such that the view dtype fits in the
| | array dtype; for example an array of dtype complex128 has 16-byte elements.
| | If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| | between 0 and 12 bytes.
| |
| | Parameters
| | ----------
| | dtype : str or dtype
| | The data type of the view. The dtype size of the view can not be larger
| | than that of the array itself.
| | offset : int
| | Number of bytes to skip before beginning the element view.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.diag([1.+1.j]*2)
| | >>> x[1, 1] = 2 + 4.j
| | >>> x
| | array([[1.+1.j, 0.+0.j],
| | [0.+0.j, 2.+4.j]])
| | >>> x.getfield(np.float64)
| | array([[1., 0.],
| | [0., 2.]])
| |
| | By choosing an offset of 8 bytes we can select the complex part of the
| | array for our view:
| |
| | >>> x.getfield(np.float64, offset=8)
| | array([[1., 0.],
| | [0., 4.]])
| |
| | item(...)
| | a.item(*args)
| |
| | Copy an element of an array to a standard Python scalar and return it.
| |
| | Parameters
| | ----------
| | \*args : Arguments (variable number and type)
| |
| | * none: in this case, the method only works for arrays
| | with one element (`a.size == 1`), which element is
| | copied into a standard Python scalar object and returned.
| |
| | * int_type: this argument is interpreted as a flat index into
| | the array, specifying which element to copy and return.
| |
| | * tuple of int_types: functions as does a single int_type argument,
| | except that the argument is interpreted as an nd-index into the
| | array.
| |
| | Returns
| | -------
| | z : Standard Python scalar object
| | A copy of the specified element of the array as a suitable
| | Python scalar
| |
| | Notes
| | -----
| | When the data type of `a` is longdouble or clongdouble, item() returns
| | a scalar array object because there is no available Python scalar that
| | would not lose information. Void arrays return a buffer object for item(),
| | unless fields are defined, in which case a tuple is returned.
| |
| | `item` is very similar to a[args], except, instead of an array scalar,
| | a standard Python scalar is returned. This can be useful for speeding up
| | access to elements of the array and doing arithmetic on elements of the
| | array using Python's optimized math.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> np.random.seed(123)
| | >>> x = np.random.randint(9, size=(3, 3))
| | >>> x
| | array([[2, 2, 6],
| | [1, 3, 6],
| | [1, 0, 1]])
| | >>> x.item(3)
| | 1
| | >>> x.item(7)
| | 0
| | >>> x.item((0, 1))
| | 2
| | >>> x.item((2, 2))
| | 1
| |
| | For an array with object dtype, elements are returned as-is.
| |
| | >>> a = np.array([np.int64(1)], dtype=object)
| | >>> a.item() #return np.int64
| | np.int64(1)
| |
| | nonzero(...)
| | a.nonzero()
| |
| | Return the indices of the elements that are non-zero.
| |
| | Refer to `numpy.nonzero` for full documentation.
| |
| | See Also
| | --------
| | numpy.nonzero : equivalent function
| |
| | partition(...)
| | a.partition(kth, axis=-1, kind='introselect', order=None)
| |
| | Partially sorts the elements in the array 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. In the output array, all elements smaller than the k-th element
| | are located to the left of this element and all equal or greater are
| | located to its right. The ordering of the elements in the two partitions
| | on the either side of the k-th element in the output array is undefined.
| |
| | .. versionadded:: 1.8.0
| |
| | Parameters
| | ----------
| | kth : int or sequence of ints
| | Element index to partition by. The kth element value 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 kth it will partition all elements
| | indexed by kth of them into their sorted position at once.
| |
| | .. deprecated:: 1.22.0
| | Passing booleans as index is deprecated.
| | axis : int, optional
| | Axis along which to sort. Default is -1, which means sort along the
| | last axis.
| | kind : {'introselect'}, optional
| | Selection algorithm. Default is 'introselect'.
| | order : str 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, and not all fields need to be specified,
| | but unspecified fields will still be used, in the order in which
| | they come up in the dtype, to break ties.
| |
| | See Also
| | --------
| | numpy.partition : Return a partitioned copy of an array.
| | argpartition : Indirect partition.
| | sort : Full sort.
| |
| | Notes
| | -----
| | See ``np.partition`` for notes on the different algorithms.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.array([3, 4, 2, 1])
| | >>> a.partition(3)
| | >>> a
| | array([2, 1, 3, 4]) # may vary
| |
| | >>> a.partition((1, 3))
| | >>> a
| | array([1, 2, 3, 4])
| |
| | put(...)
| | a.put(indices, values, mode='raise')
| |
| | Set ``a.flat[n] = values[n]`` for all `n` in indices.
| |
| | Refer to `numpy.put` for full documentation.
| |
| | See Also
| | --------
| | numpy.put : equivalent function
| |
| | repeat(...)
| | a.repeat(repeats, axis=None)
| |
| | Repeat elements of an array.
| |
| | Refer to `numpy.repeat` for full documentation.
| |
| | See Also
| | --------
| | numpy.repeat : equivalent function
| |
| | reshape(...)
| | a.reshape(shape, /, *, order='C', copy=None)
| |
| | Returns an array containing the same data with a new shape.
| |
| | Refer to `numpy.reshape` for full documentation.
| |
| | See Also
| | --------
| | numpy.reshape : equivalent function
| |
| | Notes
| | -----
| | Unlike the free function `numpy.reshape`, this method on `ndarray` allows
| | the elements of the shape parameter to be passed in as separate arguments.
| | For example, ``a.reshape(10, 11)`` is equivalent to
| | ``a.reshape((10, 11))``.
| |
| | resize(...)
| | a.resize(new_shape, refcheck=True)
| |
| | Change shape and size of array in-place.
| |
| | Parameters
| | ----------
| | new_shape : tuple of ints, or `n` ints
| | Shape of resized array.
| | refcheck : bool, optional
| | If False, reference count will not be checked. Default is True.
| |
| | Returns
| | -------
| | None
| |
| | Raises
| | ------
| | ValueError
| | If `a` does not own its own data or references or views to it exist,
| | and the data memory must be changed.
| | PyPy only: will always raise if the data memory must be changed, since
| | there is no reliable way to determine if references or views to it
| | exist.
| |
| | SystemError
| | If the `order` keyword argument is specified. This behaviour is a
| | bug in NumPy.
| |
| | See Also
| | --------
| | resize : Return a new array with the specified shape.
| |
| | Notes
| | -----
| | This reallocates space for the data area if necessary.
| |
| | Only contiguous arrays (data elements consecutive in memory) can be
| | resized.
| |
| | The purpose of the reference count check is to make sure you
| | do not use this array as a buffer for another Python object and then
| | reallocate the memory. However, reference counts can increase in
| | other ways so if you are sure that you have not shared the memory
| | for this array with another Python object, then you may safely set
| | `refcheck` to False.
| |
| | Examples
| | --------
| | Shrinking an array: array is flattened (in the order that the data are
| | stored in memory), resized, and reshaped:
| |
| | >>> import numpy as np
| |
| | >>> a = np.array([[0, 1], [2, 3]], order='C')
| | >>> a.resize((2, 1))
| | >>> a
| | array([[0],
| | [1]])
| |
| | >>> a = np.array([[0, 1], [2, 3]], order='F')
| | >>> a.resize((2, 1))
| | >>> a
| | array([[0],
| | [2]])
| |
| | Enlarging an array: as above, but missing entries are filled with zeros:
| |
| | >>> b = np.array([[0, 1], [2, 3]])
| | >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
| | >>> b
| | array([[0, 1, 2],
| | [3, 0, 0]])
| |
| | Referencing an array prevents resizing...
| |
| | >>> c = a
| | >>> a.resize((1, 1))
| | Traceback (most recent call last):
| | ...
| | ValueError: cannot resize an array that references or is referenced ...
| |
| | Unless `refcheck` is False:
| |
| | >>> a.resize((1, 1), refcheck=False)
| | >>> a
| | array([[0]])
| | >>> c
| | array([[0]])
| |
| | round(...)
| | a.round(decimals=0, out=None)
| |
| | Return `a` with each element rounded to the given number of decimals.
| |
| | Refer to `numpy.around` for full documentation.
| |
| | See Also
| | --------
| | numpy.around : equivalent function
| |
| | searchsorted(...)
| | a.searchsorted(v, side='left', sorter=None)
| |
| | Find indices where elements of v should be inserted in a to maintain order.
| |
| | For full documentation, see `numpy.searchsorted`
| |
| | See Also
| | --------
| | numpy.searchsorted : equivalent function
| |
| | setfield(...)
| | a.setfield(val, dtype, offset=0)
| |
| | Put a value into a specified place in a field defined by a data-type.
| |
| | Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| | bytes into the field.
| |
| | Parameters
| | ----------
| | val : object
| | Value to be placed in field.
| | dtype : dtype object
| | Data-type of the field in which to place `val`.
| | offset : int, optional
| | The number of bytes into the field at which to place `val`.
| |
| | Returns
| | -------
| | None
| |
| | See Also
| | --------
| | getfield
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.eye(3)
| | >>> x.getfield(np.float64)
| | array([[1., 0., 0.],
| | [0., 1., 0.],
| | [0., 0., 1.]])
| | >>> x.setfield(3, np.int32)
| | >>> x.getfield(np.int32)
| | array([[3, 3, 3],
| | [3, 3, 3],
| | [3, 3, 3]], dtype=int32)
| | >>> x
| | array([[1.0e+000, 1.5e-323, 1.5e-323],
| | [1.5e-323, 1.0e+000, 1.5e-323],
| | [1.5e-323, 1.5e-323, 1.0e+000]])
| | >>> x.setfield(np.eye(3), np.int32)
| | >>> x
| | array([[1., 0., 0.],
| | [0., 1., 0.],
| | [0., 0., 1.]])
| |
| | setflags(...)
| | a.setflags(write=None, align=None, uic=None)
| |
| | Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| | respectively.
| |
| | These Boolean-valued flags affect how numpy interprets the memory
| | area used by `a` (see Notes below). The ALIGNED flag can only
| | be set to True if the data is actually aligned according to the type.
| | The WRITEBACKIFCOPY flag can never be set
| | to True. The flag WRITEABLE can only be set to True if the array owns its
| | own memory, or the ultimate owner of the memory exposes a writeable buffer
| | interface, or is a string. (The exception for string is made so that
| | unpickling can be done without copying memory.)
| |
| | Parameters
| | ----------
| | write : bool, optional
| | Describes whether or not `a` can be written to.
| | align : bool, optional
| | Describes whether or not `a` is aligned properly for its type.
| | uic : bool, optional
| | Describes whether or not `a` is a copy of another "base" array.
| |
| | Notes
| | -----
| | Array flags provide information about how the memory area used
| | for the array is to be interpreted. There are 7 Boolean flags
| | in use, only three of which can be changed by the user:
| | WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
| |
| | WRITEABLE (W) the data area can be written to;
| |
| | ALIGNED (A) the data and strides are aligned appropriately for the hardware
| | (as determined by the compiler);
| |
| | WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| | by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| | called, the base array will be updated with the contents of this array.
| |
| | All flags can be accessed using the single (upper case) letter as well
| | as the full name.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> y = np.array([[3, 1, 7],
| | ... [2, 0, 0],
| | ... [8, 5, 9]])
| | >>> y
| | array([[3, 1, 7],
| | [2, 0, 0],
| | [8, 5, 9]])
| | >>> y.flags
| | C_CONTIGUOUS : True
| | F_CONTIGUOUS : False
| | OWNDATA : True
| | WRITEABLE : True
| | ALIGNED : True
| | WRITEBACKIFCOPY : False
| | >>> y.setflags(write=0, align=0)
| | >>> y.flags
| | C_CONTIGUOUS : True
| | F_CONTIGUOUS : False
| | OWNDATA : True
| | WRITEABLE : False
| | ALIGNED : False
| | WRITEBACKIFCOPY : False
| | >>> y.setflags(uic=1)
| | Traceback (most recent call last):
| | File "<stdin>", line 1, in <module>
| | ValueError: cannot set WRITEBACKIFCOPY flag to True
| |
| | sort(...)
| | a.sort(axis=-1, kind=None, order=None)
| |
| | Sort an array in-place. Refer to `numpy.sort` for full documentation.
| |
| | Parameters
| | ----------
| | axis : int, optional
| | Axis along which to sort. Default is -1, which means sort along the
| | last axis.
| | kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| | Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
| | and 'mergesort' use timsort under the covers and, in general, the
| | actual implementation will vary with datatype. The 'mergesort' option
| | is retained for backwards compatibility.
| |
| | .. versionchanged:: 1.15.0
| | The 'stable' option was added.
| |
| | order : str 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, and 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.
| |
| | See Also
| | --------
| | numpy.sort : Return a sorted copy of an array.
| | numpy.argsort : Indirect sort.
| | numpy.lexsort : Indirect stable sort on multiple keys.
| | numpy.searchsorted : Find elements in sorted array.
| | numpy.partition: Partial sort.
| |
| | Notes
| | -----
| | See `numpy.sort` for notes on the different sorting algorithms.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.array([[1,4], [3,1]])
| | >>> a.sort(axis=1)
| | >>> a
| | array([[1, 4],
| | [1, 3]])
| | >>> a.sort(axis=0)
| | >>> a
| | array([[1, 3],
| | [1, 4]])
| |
| | Use the `order` keyword to specify a field to use when sorting a
| | structured array:
| |
| | >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
| | >>> a.sort(order='y')
| | >>> a
| | array([(b'c', 1), (b'a', 2)],
| | dtype=[('x', 'S1'), ('y', '<i8')])
| |
| | swapaxes(...)
| | a.swapaxes(axis1, axis2)
| |
| | Return a view of the array with `axis1` and `axis2` interchanged.
| |
| | Refer to `numpy.swapaxes` for full documentation.
| |
| | See Also
| | --------
| | numpy.swapaxes : equivalent function
| |
| | take(...)
| | a.take(indices, axis=None, out=None, mode='raise')
| |
| | Return an array formed from the elements of `a` at the given indices.
| |
| | Refer to `numpy.take` for full documentation.
| |
| | See Also
| | --------
| | numpy.take : equivalent function
| |
| | to_device(...)
| |
| | tobytes(...)
| | a.tobytes(order='C')
| |
| | Construct Python bytes containing the raw data bytes in the array.
| |
| | Constructs Python bytes showing a copy of the raw contents of
| | data memory. The bytes object is produced in C-order by default.
| | This behavior is controlled by the ``order`` parameter.
| |
| | .. versionadded:: 1.9.0
| |
| | Parameters
| | ----------
| | order : {'C', 'F', 'A'}, optional
| | Controls the memory layout of the bytes object. 'C' means C-order,
| | 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
| | Fortran contiguous, 'C' otherwise. Default is 'C'.
| |
| | Returns
| | -------
| | s : bytes
| | Python bytes exhibiting a copy of `a`'s raw data.
| |
| | See also
| | --------
| | frombuffer
| | Inverse of this operation, construct a 1-dimensional array from Python
| | bytes.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
| | >>> x.tobytes()
| | b'\x00\x00\x01\x00\x02\x00\x03\x00'
| | >>> x.tobytes('C') == x.tobytes()
| | True
| | >>> x.tobytes('F')
| | b'\x00\x00\x02\x00\x01\x00\x03\x00'
| |
| | tofile(...)
| | a.tofile(fid, sep="", format="%s")
| |
| | Write array to a file as text or binary (default).
| |
| | Data is always written in 'C' order, independent of the order of `a`.
| | The data produced by this method can be recovered using the function
| | fromfile().
| |
| | Parameters
| | ----------
| | fid : file or str or Path
| | An open file object, or a string containing a filename.
| |
| | .. versionchanged:: 1.17.0
| | `pathlib.Path` objects are now accepted.
| |
| | sep : str
| | Separator between array items for text output.
| | If "" (empty), a binary file is written, equivalent to
| | ``file.write(a.tobytes())``.
| | format : str
| | Format string for text file output.
| | Each entry in the array is formatted to text by first converting
| | it to the closest Python type, and then using "format" % item.
| |
| | Notes
| | -----
| | This is a convenience function for quick storage of array data.
| | Information on endianness and precision is lost, so this method is not a
| | good choice for files intended to archive data or transport data between
| | machines with different endianness. Some of these problems can be overcome
| | by outputting the data as text files, at the expense of speed and file
| | size.
| |
| | When fid is a file object, array contents are directly written to the
| | file, bypassing the file object's ``write`` method. As a result, tofile
| | cannot be used with files objects supporting compression (e.g., GzipFile)
| | or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
| |
| | tostring(...)
| | a.tostring(order='C')
| |
| | A compatibility alias for `~ndarray.tobytes`, with exactly the same
| | behavior.
| |
| | Despite its name, it returns :class:`bytes` not :class:`str`\ s.
| |
| | .. deprecated:: 1.19.0
| |
| | trace(...)
| | a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
| |
| | Return the sum along diagonals of the array.
| |
| | Refer to `numpy.trace` for full documentation.
| |
| | See Also
| | --------
| | numpy.trace : equivalent function
| |
| | transpose(...)
| | a.transpose(*axes)
| |
| | Returns a view of the array with axes transposed.
| |
| | Refer to `numpy.transpose` for full documentation.
| |
| | Parameters
| | ----------
| | axes : None, tuple of ints, or `n` ints
| |
| | * None or no argument: reverses the order of the axes.
| |
| | * tuple of ints: `i` in the `j`-th place in the tuple means that the
| | array's `i`-th axis becomes the transposed array's `j`-th axis.
| |
| | * `n` ints: same as an n-tuple of the same ints (this form is
| | intended simply as a "convenience" alternative to the tuple form).
| |
| | Returns
| | -------
| | p : ndarray
| | View of the array with its axes suitably permuted.
| |
| | See Also
| | --------
| | transpose : Equivalent function.
| | ndarray.T : Array property returning the array transposed.
| | ndarray.reshape : Give a new shape to an array without changing its data.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.array([[1, 2], [3, 4]])
| | >>> a
| | array([[1, 2],
| | [3, 4]])
| | >>> a.transpose()
| | array([[1, 3],
| | [2, 4]])
| | >>> a.transpose((1, 0))
| | array([[1, 3],
| | [2, 4]])
| | >>> a.transpose(1, 0)
| | array([[1, 3],
| | [2, 4]])
| |
| | >>> a = np.array([1, 2, 3, 4])
| | >>> a
| | array([1, 2, 3, 4])
| | >>> a.transpose()
| | array([1, 2, 3, 4])
| |
| | view(...)
| | a.view([dtype][, type])
| |
| | New view of array with the same data.
| |
| | .. note::
| | Passing None for ``dtype`` is different from omitting the parameter,
| | since the former invokes ``dtype(None)`` which is an alias for
| | ``dtype('float64')``.
| |
| | Parameters
| | ----------
| | dtype : data-type or ndarray sub-class, optional
| | Data-type descriptor of the returned view, e.g., float32 or int16.
| | Omitting it results in the view having the same data-type as `a`.
| | This argument can also be specified as an ndarray sub-class, which
| | then specifies the type of the returned object (this is equivalent to
| | setting the ``type`` parameter).
| | type : Python type, optional
| | Type of the returned view, e.g., ndarray or matrix. Again, omission
| | of the parameter results in type preservation.
| |
| | Notes
| | -----
| | ``a.view()`` is used two different ways:
| |
| | ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| | of the array's memory with a different data-type. This can cause a
| | reinterpretation of the bytes of memory.
| |
| | ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| | returns an instance of `ndarray_subclass` that looks at the same array
| | (same shape, dtype, etc.) This does not cause a reinterpretation of the
| | memory.
| |
| | For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| | bytes per entry than the previous dtype (for example, converting a regular
| | array to a structured array), then the last axis of ``a`` must be
| | contiguous. This axis will be resized in the result.
| |
| | .. versionchanged:: 1.23.0
| | Only the last axis needs to be contiguous. Previously, the entire array
| | had to be C-contiguous.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
| |
| | Viewing array data using a different type and dtype:
| |
| | >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
| | >>> y = x.view(dtype=nonneg, type=np.recarray)
| | >>> x["a"]
| | array([-1], dtype=int8)
| | >>> y.a
| | array([255], dtype=uint8)
| |
| | Creating a view on a structured array so it can be used in calculations
| |
| | >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
| | >>> xv = x.view(dtype=np.int8).reshape(-1,2)
| | >>> xv
| | array([[1, 2],
| | [3, 4]], dtype=int8)
| | >>> xv.mean(0)
| | array([2., 3.])
| |
| | Making changes to the view changes the underlying array
| |
| | >>> xv[0,1] = 20
| | >>> x
| | array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
| |
| | Using a view to convert an array to a recarray:
| |
| | >>> z = x.view(np.recarray)
| | >>> z.a
| | array([1, 3], dtype=int8)
| |
| | Views share data:
| |
| | >>> x[0] = (9, 10)
| | >>> z[0]
| | np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
| |
| | Views that change the dtype size (bytes per entry) should normally be
| | avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
| |
| | >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
| | >>> y = x[:, ::2]
| | >>> y
| | array([[1, 3],
| | [4, 6]], dtype=int16)
| | >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
| | Traceback (most recent call last):
| | ...
| | ValueError: To change to a dtype of a different size, the last axis must be contiguous
| | >>> z = y.copy()
| | >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
| | array([[(1, 3)],
| | [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
| |
| | However, views that change dtype are totally fine for arrays with a
| | contiguous last axis, even if the rest of the axes are not C-contiguous:
| |
| | >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
| | >>> x.transpose(1, 0, 2).view(np.int16)
| | array([[[ 256, 770],
| | [3340, 3854]],
| | <BLANKLINE>
| | [[1284, 1798],
| | [4368, 4882]],
| | <BLANKLINE>
| | [[2312, 2826],
| | [5396, 5910]]], dtype=int16)
| |
| | ----------------------------------------------------------------------
| | Class methods inherited from ndarray:
| |
| | __class_getitem__(...)
| | a.__class_getitem__(item, /)
| |
| | Return a parametrized wrapper around the `~numpy.ndarray` type.
| |
| | .. versionadded:: 1.22
| |
| | Returns
| | -------
| | alias : types.GenericAlias
| | A parametrized `~numpy.ndarray` type.
| |
| | Examples
| | --------
| | >>> from typing import Any
| | >>> import numpy as np
| |
| | >>> np.ndarray[Any, np.dtype[Any]]
| | numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
| |
| | See Also
| | --------
| | :pep:`585` : Type hinting generics in standard collections.
| | numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| | w.r.t. its `dtype.type <numpy.dtype.type>`.
| |
| | ----------------------------------------------------------------------
| | Data descriptors inherited from ndarray:
| |
| | __array_interface__
| | Array protocol: Python side.
| |
| | __array_struct__
| | Array protocol: C-struct side.
| |
| | base
| | Base object if memory is from some other object.
| |
| | Examples
| | --------
| | The base of an array that owns its memory is None:
| |
| | >>> import numpy as np
| | >>> x = np.array([1,2,3,4])
| | >>> x.base is None
| | True
| |
| | Slicing creates a view, whose memory is shared with x:
| |
| | >>> y = x[2:]
| | >>> y.base is x
| | True
| |
| | ctypes
| | An object to simplify the interaction of the array with the ctypes
| | module.
| |
| | This attribute creates an object that makes it easier to use arrays
| | when calling shared libraries with the ctypes module. The returned
| | object has, among others, data, shape, and strides attributes (see
| | Notes below) which themselves return ctypes objects that can be used
| | as arguments to a shared library.
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | c : Python object
| | Possessing attributes data, shape, strides, etc.
| |
| | See Also
| | --------
| | numpy.ctypeslib
| |
| | Notes
| | -----
| | Below are the public attributes of this object which were documented
| | in "Guide to NumPy" (we have omitted undocumented public attributes,
| | as well as documented private attributes):
| |
| | .. autoattribute:: numpy._core._internal._ctypes.data
| | :noindex:
| |
| | .. autoattribute:: numpy._core._internal._ctypes.shape
| | :noindex:
| |
| | .. autoattribute:: numpy._core._internal._ctypes.strides
| | :noindex:
| |
| | .. automethod:: numpy._core._internal._ctypes.data_as
| | :noindex:
| |
| | .. automethod:: numpy._core._internal._ctypes.shape_as
| | :noindex:
| |
| | .. automethod:: numpy._core._internal._ctypes.strides_as
| | :noindex:
| |
| | If the ctypes module is not available, then the ctypes attribute
| | of array objects still returns something useful, but ctypes objects
| | are not returned and errors may be raised instead. In particular,
| | the object will still have the ``as_parameter`` attribute which will
| | return an integer equal to the data attribute.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> import ctypes
| | >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| | >>> x
| | array([[0, 1],
| | [2, 3]], dtype=int32)
| | >>> x.ctypes.data
| | 31962608 # may vary
| | >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| | <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| | >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| | c_uint(0)
| | >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| | c_ulong(4294967296)
| | >>> x.ctypes.shape
| | <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| | >>> x.ctypes.strides
| | <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
| |
| | data
| | Python buffer object pointing to the start of the array's data.
| |
| | device
| |
| | dtype
| | Data-type of the array's elements.
| |
| | .. warning::
| |
| | Setting ``arr.dtype`` is discouraged and may be deprecated in the
| | future. Setting will replace the ``dtype`` without modifying the
| | memory (see also `ndarray.view` and `ndarray.astype`).
| |
| | Parameters
| | ----------
| | None
| |
| | Returns
| | -------
| | d : numpy dtype object
| |
| | See Also
| | --------
| | ndarray.astype : Cast the values contained in the array to a new data-type.
| | ndarray.view : Create a view of the same data but a different data-type.
| | numpy.dtype
| |
| | Examples
| | --------
| | >>> x
| | array([[0, 1],
| | [2, 3]])
| | >>> x.dtype
| | dtype('int32')
| | >>> type(x.dtype)
| | <type 'numpy.dtype'>
| |
| | flags
| | Information about the memory layout of the array.
| |
| | Attributes
| | ----------
| | C_CONTIGUOUS (C)
| | The data is in a single, C-style contiguous segment.
| | F_CONTIGUOUS (F)
| | The data is in a single, Fortran-style contiguous segment.
| | OWNDATA (O)
| | The array owns the memory it uses or borrows it from another object.
| | WRITEABLE (W)
| | The data area can be written to. Setting this to False locks
| | the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| | from its base array at creation time, but a view of a writeable
| | array may be subsequently locked while the base array remains writeable.
| | (The opposite is not true, in that a view of a locked array may not
| | be made writeable. However, currently, locking a base object does not
| | lock any views that already reference it, so under that circumstance it
| | is possible to alter the contents of a locked array via a previously
| | created writeable view onto it.) Attempting to change a non-writeable
| | array raises a RuntimeError exception.
| | ALIGNED (A)
| | The data and all elements are aligned appropriately for the hardware.
| | WRITEBACKIFCOPY (X)
| | This array is a copy of some other array. The C-API function
| | PyArray_ResolveWritebackIfCopy must be called before deallocating
| | to the base array will be updated with the contents of this array.
| | FNC
| | F_CONTIGUOUS and not C_CONTIGUOUS.
| | FORC
| | F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| | BEHAVED (B)
| | ALIGNED and WRITEABLE.
| | CARRAY (CA)
| | BEHAVED and C_CONTIGUOUS.
| | FARRAY (FA)
| | BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
| |
| | Notes
| | -----
| | The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| | or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| | names are only supported in dictionary access.
| |
| | Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| | changed by the user, via direct assignment to the attribute or dictionary
| | entry, or by calling `ndarray.setflags`.
| |
| | The array flags cannot be set arbitrarily:
| |
| | - WRITEBACKIFCOPY can only be set ``False``.
| | - ALIGNED can only be set ``True`` if the data is truly aligned.
| | - WRITEABLE can only be set ``True`` if the array owns its own memory
| | or the ultimate owner of the memory exposes a writeable buffer
| | interface or is a string.
| |
| | Arrays can be both C-style and Fortran-style contiguous simultaneously.
| | This is clear for 1-dimensional arrays, but can also be true for higher
| | dimensional arrays.
| |
| | Even for contiguous arrays a stride for a given dimension
| | ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| | or the array has no elements.
| | It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| | for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| | Fortran-style contiguous arrays is true.
| |
| | flat
| | A 1-D iterator over the array.
| |
| | This is a `numpy.flatiter` instance, which acts similarly to, but is not
| | a subclass of, Python's built-in iterator object.
| |
| | See Also
| | --------
| | flatten : Return a copy of the array collapsed into one dimension.
| |
| | flatiter
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.arange(1, 7).reshape(2, 3)
| | >>> x
| | array([[1, 2, 3],
| | [4, 5, 6]])
| | >>> x.flat[3]
| | 4
| | >>> x.T
| | array([[1, 4],
| | [2, 5],
| | [3, 6]])
| | >>> x.T.flat[3]
| | 5
| | >>> type(x.flat)
| | <class 'numpy.flatiter'>
| |
| | An assignment example:
| |
| | >>> x.flat = 3; x
| | array([[3, 3, 3],
| | [3, 3, 3]])
| | >>> x.flat[[1,4]] = 1; x
| | array([[3, 1, 3],
| | [3, 1, 3]])
| |
| | imag
| | The imaginary part of the array.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.sqrt([1+0j, 0+1j])
| | >>> x.imag
| | array([ 0. , 0.70710678])
| | >>> x.imag.dtype
| | dtype('float64')
| |
| | itemset
| |
| | itemsize
| | Length of one array element in bytes.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([1,2,3], dtype=np.float64)
| | >>> x.itemsize
| | 8
| | >>> x = np.array([1,2,3], dtype=np.complex128)
| | >>> x.itemsize
| | 16
| |
| | mT
| | View of the matrix transposed array.
| |
| | The matrix transpose is the transpose of the last two dimensions, even
| | if the array is of higher dimension.
| |
| | .. versionadded:: 2.0
| |
| | Raises
| | ------
| | ValueError
| | If the array is of dimension less than 2.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> a = np.array([[1, 2], [3, 4]])
| | >>> a
| | array([[1, 2],
| | [3, 4]])
| | >>> a.mT
| | array([[1, 3],
| | [2, 4]])
| |
| | >>> a = np.arange(8).reshape((2, 2, 2))
| | >>> a
| | array([[[0, 1],
| | [2, 3]],
| | <BLANKLINE>
| | [[4, 5],
| | [6, 7]]])
| | >>> a.mT
| | array([[[0, 2],
| | [1, 3]],
| | <BLANKLINE>
| | [[4, 6],
| | [5, 7]]])
| |
| | nbytes
| | Total bytes consumed by the elements of the array.
| |
| | Notes
| | -----
| | Does not include memory consumed by non-element attributes of the
| | array object.
| |
| | See Also
| | --------
| | sys.getsizeof
| | Memory consumed by the object itself without parents in case view.
| | This does include memory consumed by non-element attributes.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.zeros((3,5,2), dtype=np.complex128)
| | >>> x.nbytes
| | 480
| | >>> np.prod(x.shape) * x.itemsize
| | 480
| |
| | ndim
| | Number of array dimensions.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([1, 2, 3])
| | >>> x.ndim
| | 1
| | >>> y = np.zeros((2, 3, 4))
| | >>> y.ndim
| | 3
| |
| | newbyteorder
| |
| | real
| | The real part of the array.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.sqrt([1+0j, 0+1j])
| | >>> x.real
| | array([ 1. , 0.70710678])
| | >>> x.real.dtype
| | dtype('float64')
| |
| | See Also
| | --------
| | numpy.real : equivalent function
| |
| | shape
| | Tuple of array dimensions.
| |
| | The shape property is usually used to get the current shape of an array,
| | but may also be used to reshape the array in-place by assigning a tuple of
| | array dimensions to it. As with `numpy.reshape`, one of the new shape
| | dimensions can be -1, in which case its value is inferred from the size of
| | the array and the remaining dimensions. Reshaping an array in-place will
| | fail if a copy is required.
| |
| | .. warning::
| |
| | Setting ``arr.shape`` is discouraged and may be deprecated in the
| | future. Using `ndarray.reshape` is the preferred approach.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.array([1, 2, 3, 4])
| | >>> x.shape
| | (4,)
| | >>> y = np.zeros((2, 3, 4))
| | >>> y.shape
| | (2, 3, 4)
| | >>> y.shape = (3, 8)
| | >>> y
| | array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| | [ 0., 0., 0., 0., 0., 0., 0., 0.],
| | [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| | >>> y.shape = (3, 6)
| | Traceback (most recent call last):
| | File "<stdin>", line 1, in <module>
| | ValueError: total size of new array must be unchanged
| | >>> np.zeros((4,2))[::2].shape = (-1,)
| | Traceback (most recent call last):
| | File "<stdin>", line 1, in <module>
| | AttributeError: Incompatible shape for in-place modification. Use
| | `.reshape()` to make a copy with the desired shape.
| |
| | See Also
| | --------
| | numpy.shape : Equivalent getter function.
| | numpy.reshape : Function similar to setting ``shape``.
| | ndarray.reshape : Method similar to setting ``shape``.
| |
| | size
| | Number of elements in the array.
| |
| | Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| | dimensions.
| |
| | Notes
| | -----
| | `a.size` returns a standard arbitrary precision Python integer. This
| | may not be the case with other methods of obtaining the same value
| | (like the suggested ``np.prod(a.shape)``, which returns an instance
| | of ``np.int_``), and may be relevant if the value is used further in
| | calculations that may overflow a fixed size integer type.
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| | >>> x.size
| | 30
| | >>> np.prod(x.shape)
| | 30
| |
| | strides
| | Tuple of bytes to step in each dimension when traversing an array.
| |
| | The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| | is::
| |
| | offset = sum(np.array(i) * a.strides)
| |
| | A more detailed explanation of strides can be found in
| | :ref:`arrays.ndarray`.
| |
| | .. warning::
| |
| | Setting ``arr.strides`` is discouraged and may be deprecated in the
| | future. `numpy.lib.stride_tricks.as_strided` should be preferred
| | to create a new view of the same data in a safer way.
| |
| | Notes
| | -----
| | Imagine an array of 32-bit integers (each 4 bytes)::
| |
| | x = np.array([[0, 1, 2, 3, 4],
| | [5, 6, 7, 8, 9]], dtype=np.int32)
| |
| | This array is stored in memory as 40 bytes, one after the other
| | (known as a contiguous block of memory). The strides of an array tell
| | us how many bytes we have to skip in memory to move to the next position
| | along a certain axis. For example, we have to skip 4 bytes (1 value) to
| | move to the next column, but 20 bytes (5 values) to get to the same
| | position in the next row. As such, the strides for the array `x` will be
| | ``(20, 4)``.
| |
| | See Also
| | --------
| | numpy.lib.stride_tricks.as_strided
| |
| | Examples
| | --------
| | >>> import numpy as np
| | >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| | >>> y
| | array([[[ 0, 1, 2, 3],
| | [ 4, 5, 6, 7],
| | [ 8, 9, 10, 11]],
| | [[12, 13, 14, 15],
| | [16, 17, 18, 19],
| | [20, 21, 22, 23]]])
| | >>> y.strides
| | (48, 16, 4)
| | >>> y[1,1,1]
| | 17
| | >>> offset=sum(y.strides * np.array((1,1,1)))
| | >>> offset/y.itemsize
| | 17
| |
| | >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| | >>> x.strides
| | (32, 4, 224, 1344)
| | >>> i = np.array([3,5,2,2])
| | >>> offset = sum(i * x.strides)
| | >>> x[3,5,2,2]
| | 813
| | >>> offset / x.itemsize
| | 813
| |
| | ----------------------------------------------------------------------
| | Data and other attributes inherited from ndarray:
| |
| | __hash__ = None
|
| ----------------------------------------------------------------------
| Data descriptors inherited from AxisConcatenator:
|
| axis
|
| matrix
|
| ndmin
|
| trans1d
numpy.rad2deg
Python Library Documentation: ufunc
rad2deg = <ufunc 'rad2deg'>
rad2deg(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Convert angles from radians to degrees.
Parameters
----------
x : array_like
Angle in radians.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding angle in degrees.
This is a scalar if `x` is a scalar.
See Also
--------
deg2rad : Convert angles from degrees to radians.
unwrap : Remove large jumps in angle by wrapping.
Notes
-----
.. versionadded:: 1.3.0
rad2deg(x) is ``180 * x / pi``.
Examples
--------
>>> import numpy as np
>>> np.rad2deg(np.pi/2)
90.0
numpy.radians
Python Library Documentation: ufunc
radians = <ufunc 'radians'>
radians(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Convert angles from degrees to radians.
Parameters
----------
x : array_like
Input array in degrees.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding radian values.
This is a scalar if `x` is a scalar.
See Also
--------
deg2rad : equivalent function
Examples
--------
>>> import numpy as np
Convert a degree array to radians
>>> deg = np.arange(12.) * 30.
>>> np.radians(deg)
array([ 0. , 0.52359878, 1.04719755, 1.57079633, 2.0943951 ,
2.61799388, 3.14159265, 3.66519143, 4.1887902 , 4.71238898,
5.23598776, 5.75958653])
>>> out = np.zeros((deg.shape))
>>> ret = np.radians(deg, out)
>>> ret is out
True
numpy.random
Python Library Documentation: package numpy.random in numpy
NAME
numpy.random
DESCRIPTION
========================
Random Number Generation
========================
Use ``default_rng()`` to create a `Generator` and call its methods.
=============== =========================================================
Generator
--------------- ---------------------------------------------------------
Generator Class implementing all of the random number distributions
default_rng Default constructor for ``Generator``
=============== =========================================================
============================================= ===
BitGenerator Streams that work with Generator
--------------------------------------------- ---
MT19937
PCG64
PCG64DXSM
Philox
SFC64
============================================= ===
============================================= ===
Getting entropy to initialize a BitGenerator
--------------------------------------------- ---
SeedSequence
============================================= ===
Legacy
------
For backwards compatibility with previous versions of numpy before 1.17, the
various aliases to the global `RandomState` methods are left alone and do not
use the new `Generator` API.
==================== =========================================================
Utility functions
-------------------- ---------------------------------------------------------
random Uniformly distributed floats over ``[0, 1)``
bytes Uniformly distributed random bytes.
permutation Randomly permute a sequence / generate a random sequence.
shuffle Randomly permute a sequence in place.
choice Random sample from 1-D array.
==================== =========================================================
==================== =========================================================
Compatibility
functions - removed
in the new API
-------------------- ---------------------------------------------------------
rand Uniformly distributed values.
randn Normally distributed values.
ranf Uniformly distributed floating point numbers.
random_integers Uniformly distributed integers in a given range.
(deprecated, use ``integers(..., closed=True)`` instead)
random_sample Alias for `random_sample`
randint Uniformly distributed integers in a given range
seed Seed the legacy random number generator.
==================== =========================================================
==================== =========================================================
Univariate
distributions
-------------------- ---------------------------------------------------------
beta Beta distribution over ``[0, 1]``.
binomial Binomial distribution.
chisquare :math:`\chi^2` distribution.
exponential Exponential distribution.
f F (Fisher-Snedecor) distribution.
gamma Gamma distribution.
geometric Geometric distribution.
gumbel Gumbel distribution.
hypergeometric Hypergeometric distribution.
laplace Laplace distribution.
logistic Logistic distribution.
lognormal Log-normal distribution.
logseries Logarithmic series distribution.
negative_binomial Negative binomial distribution.
noncentral_chisquare Non-central chi-square distribution.
noncentral_f Non-central F distribution.
normal Normal / Gaussian distribution.
pareto Pareto distribution.
poisson Poisson distribution.
power Power distribution.
rayleigh Rayleigh distribution.
triangular Triangular distribution.
uniform Uniform distribution.
vonmises Von Mises circular distribution.
wald Wald (inverse Gaussian) distribution.
weibull Weibull distribution.
zipf Zipf's distribution over ranked data.
==================== =========================================================
==================== ==========================================================
Multivariate
distributions
-------------------- ----------------------------------------------------------
dirichlet Multivariate generalization of Beta distribution.
multinomial Multivariate generalization of the binomial distribution.
multivariate_normal Multivariate generalization of the normal distribution.
==================== ==========================================================
==================== =========================================================
Standard
distributions
-------------------- ---------------------------------------------------------
standard_cauchy Standard Cauchy-Lorentz distribution.
standard_exponential Standard exponential distribution.
standard_gamma Standard Gamma distribution.
standard_normal Standard normal distribution.
standard_t Standard Student's t-distribution.
==================== =========================================================
==================== =========================================================
Internal functions
-------------------- ---------------------------------------------------------
get_state Get tuple representing internal state of generator.
set_state Set state of generator.
==================== =========================================================
PACKAGE CONTENTS
_bounded_integers
_common
_generator
_mt19937
_pcg64
_philox
_pickle
_sfc64
bit_generator
mtrand
tests (package)
CLASSES
builtins.object
numpy.random._generator.Generator
numpy.random.bit_generator.BitGenerator
numpy.random._mt19937.MT19937
numpy.random._pcg64.PCG64
numpy.random._pcg64.PCG64DXSM
numpy.random._philox.Philox
numpy.random._sfc64.SFC64
numpy.random.bit_generator.SeedSequence
numpy.random.mtrand.RandomState
class BitGenerator(builtins.object)
| BitGenerator(seed=None)
|
| Base Class for generic BitGenerators, which provide a stream
| of random bits based on different algorithms. Must be overridden.
|
| Parameters
| ----------
| seed : {None, int, array_like[ints], SeedSequence}, optional
| A seed to initialize the `BitGenerator`. If None, then fresh,
| unpredictable entropy will be pulled from the OS. If an ``int`` or
| ``array_like[ints]`` is passed, then it will be passed to
| `~numpy.random.SeedSequence` to derive the initial `BitGenerator` state.
| One may also pass in a `SeedSequence` instance.
| All integer values must be non-negative.
|
| Attributes
| ----------
| lock : threading.Lock
| Lock instance that is shared so that the same BitGenerator can
| be used in multiple Generators without corrupting the state. Code that
| generates values from a bit generator should hold the bit generator's
| lock.
|
| See Also
| --------
| SeedSequence
|
| Methods defined here:
|
| __getstate__(self)
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce__(self)
|
| __setstate__(self, state_seed_seq)
|
| random_raw(self, size=None, output=True)
| random_raw(self, size=None)
|
| Return randoms as generated by the underlying BitGenerator
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| output : bool, optional
| Output values. Used for performance testing since the generated
| values are not returned.
|
| Returns
| -------
| out : uint or ndarray
| Drawn samples.
|
| Notes
| -----
| This method directly exposes the raw underlying pseudo-random
| number generator. All values are returned as unsigned 64-bit
| values irrespective of the number of bits produced by the PRNG.
|
| See the class docstring for the number of bits returned.
|
| spawn(self, n_children)
| spawn(n_children)
|
| Create new independent child bit generators.
|
| See :ref:`seedsequence-spawn` for additional notes on spawning
| children. Some bit generators also implement ``jumped``
| as a different approach for creating independent streams.
|
| .. versionadded:: 1.25.0
|
| Parameters
| ----------
| n_children : int
|
| Returns
| -------
| child_bit_generators : list of BitGenerators
|
| Raises
| ------
| TypeError
| When the underlying SeedSequence does not implement spawning.
|
| See Also
| --------
| random.Generator.spawn, random.SeedSequence.spawn :
| Equivalent method on the generator and seed sequence.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| capsule
|
| cffi
| CFFI interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing CFFI wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| ctypes
| ctypes interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing ctypes wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| lock
|
| seed_seq
| Get the seed sequence used to initialize the bit generator.
|
| .. versionadded:: 1.25.0
|
| Returns
| -------
| seed_seq : ISeedSequence
| The SeedSequence object used to initialize the BitGenerator.
| This is normally a `np.random.SeedSequence` instance.
|
| state
| Get or set the PRNG state
|
| The base BitGenerator.state must be overridden by a subclass
|
| Returns
| -------
| state : dict
| Dictionary containing the information required to describe the
| state of the PRNG
class Generator(builtins.object)
| Generator(bit_generator)
|
| Container for the BitGenerators.
|
| `Generator` exposes a number of methods for generating random
| numbers drawn from a variety of probability distributions. In addition to
| the distribution-specific arguments, each method takes a keyword argument
| `size` that defaults to ``None``. If `size` is ``None``, then a single
| value is generated and returned. If `size` is an integer, then a 1-D
| array filled with generated values is returned. If `size` is a tuple,
| then an array with that shape is filled and returned.
|
| The function :func:`numpy.random.default_rng` will instantiate
| a `Generator` with numpy's default `BitGenerator`.
|
| **No Compatibility Guarantee**
|
| `Generator` does not provide a version compatibility guarantee. In
| particular, as better algorithms evolve the bit stream may change.
|
| Parameters
| ----------
| bit_generator : BitGenerator
| BitGenerator to use as the core generator.
|
| Notes
| -----
| The Python stdlib module :external+python:mod:`random` contains
| pseudo-random number generator with a number of methods that are similar
| to the ones available in `Generator`.
| It uses Mersenne Twister, and this bit generator can
| be accessed using `MT19937`. `Generator`, besides being
| NumPy-aware, has the advantage that it provides a much larger number
| of probability distributions to choose from.
|
| Examples
| --------
| >>> from numpy.random import Generator, PCG64
| >>> rng = Generator(PCG64())
| >>> rng.standard_normal()
| -0.203 # random
|
| See Also
| --------
| default_rng : Recommended constructor for `Generator`.
|
| Methods defined here:
|
| __getstate__(self)
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce__(self)
|
| __repr__(...)
| Return repr(self).
|
| __setstate__(self, bit_gen)
|
| __str__(self, /)
| Return str(self).
|
| beta(self, a, b, size=None)
| beta(a, b, size=None)
|
| Draw samples from a Beta distribution.
|
| The Beta distribution is a special case of the Dirichlet distribution,
| and is related to the Gamma distribution. It has the probability
| distribution function
|
| .. math:: f(x; a,b) = \frac{1}{B(\alpha, \beta)} x^{\alpha - 1}
| (1 - x)^{\beta - 1},
|
| where the normalization, B, is the beta function,
|
| .. math:: B(\alpha, \beta) = \int_0^1 t^{\alpha - 1}
| (1 - t)^{\beta - 1} dt.
|
| It is often seen in Bayesian inference and order statistics.
|
| Parameters
| ----------
| a : float or array_like of floats
| Alpha, positive (>0).
| b : float or array_like of floats
| Beta, positive (>0).
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``a`` and ``b`` are both scalars.
| Otherwise, ``np.broadcast(a, b).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized beta distribution.
|
| Examples
| --------
| The beta distribution has mean a/(a+b). If ``a == b`` and both
| are > 1, the distribution is symmetric with mean 0.5.
|
| >>> rng = np.random.default_rng()
| >>> a, b, size = 2.0, 2.0, 10000
| >>> sample = rng.beta(a=a, b=b, size=size)
| >>> np.mean(sample)
| 0.5047328775385895 # may vary
|
| Otherwise the distribution is skewed left or right according to
| whether ``a`` or ``b`` is greater. The distribution is mirror
| symmetric. See for example:
|
| >>> a, b, size = 2, 7, 10000
| >>> sample_left = rng.beta(a=a, b=b, size=size)
| >>> sample_right = rng.beta(a=b, b=a, size=size)
| >>> m_left, m_right = np.mean(sample_left), np.mean(sample_right)
| >>> print(m_left, m_right)
| 0.2238596793678923 0.7774613834041182 # may vary
| >>> print(m_left - a/(a+b))
| 0.001637457145670096 # may vary
| >>> print(m_right - b/(a+b))
| -0.0003163943736596009 # may vary
|
| Display the histogram of the two samples:
|
| >>> import matplotlib.pyplot as plt
| >>> plt.hist([sample_left, sample_right],
| ... 50, density=True, histtype='bar')
| >>> plt.show()
|
| References
| ----------
| .. [1] Wikipedia, "Beta distribution",
| https://en.wikipedia.org/wiki/Beta_distribution
|
| binomial(self, n, p, size=None)
| binomial(n, p, size=None)
|
| Draw samples from a binomial distribution.
|
| Samples are drawn from a binomial distribution with specified
| parameters, n trials and p probability of success where
| n an integer >= 0 and p is in the interval [0,1]. (n may be
| input as a float, but it is truncated to an integer in use)
|
| Parameters
| ----------
| n : int or array_like of ints
| Parameter of the distribution, >= 0. Floats are also accepted,
| but they will be truncated to integers.
| p : float or array_like of floats
| Parameter of the distribution, >= 0 and <=1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``n`` and ``p`` are both scalars.
| Otherwise, ``np.broadcast(n, p).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized binomial distribution, where
| each sample is equal to the number of successes over the n trials.
|
| See Also
| --------
| scipy.stats.binom : probability density function, distribution or
| cumulative density function, etc.
|
| Notes
| -----
| The probability density for the binomial distribution is
|
| .. math:: P(N) = \binom{n}{N}p^N(1-p)^{n-N},
|
| where :math:`n` is the number of trials, :math:`p` is the probability
| of success, and :math:`N` is the number of successes.
|
| When estimating the standard error of a proportion in a population by
| using a random sample, the normal distribution works well unless the
| product p*n <=5, where p = population proportion estimate, and n =
| number of samples, in which case the binomial distribution is used
| instead. For example, a sample of 15 people shows 4 who are left
| handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4,
| so the binomial distribution should be used in this case.
|
| References
| ----------
| .. [1] Dalgaard, Peter, "Introductory Statistics with R",
| Springer-Verlag, 2002.
| .. [2] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
| Fifth Edition, 2002.
| .. [3] Lentner, Marvin, "Elementary Applied Statistics", Bogden
| and Quigley, 1972.
| .. [4] Weisstein, Eric W. "Binomial Distribution." From MathWorld--A
| Wolfram Web Resource.
| https://mathworld.wolfram.com/BinomialDistribution.html
| .. [5] Wikipedia, "Binomial distribution",
| https://en.wikipedia.org/wiki/Binomial_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> rng = np.random.default_rng()
| >>> n, p, size = 10, .5, 10000
| >>> s = rng.binomial(n, p, 10000)
|
| Assume a company drills 9 wild-cat oil exploration wells, each with
| an estimated probability of success of ``p=0.1``. All nine wells fail.
| What is the probability of that happening?
|
| Over ``size = 20,000`` trials the probability of this happening
| is on average:
|
| >>> n, p, size = 9, 0.1, 20000
| >>> np.sum(rng.binomial(n=n, p=p, size=size) == 0)/size
| 0.39015 # may vary
|
| The following can be used to visualize a sample with ``n=100``,
| ``p=0.4`` and the corresponding probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> from scipy.stats import binom
| >>> n, p, size = 100, 0.4, 10000
| >>> sample = rng.binomial(n, p, size=size)
| >>> count, bins, _ = plt.hist(sample, 30, density=True)
| >>> x = np.arange(n)
| >>> y = binom.pmf(x, n, p)
| >>> plt.plot(x, y, linewidth=2, color='r')
|
| bytes(self, length)
| bytes(length)
|
| Return random bytes.
|
| Parameters
| ----------
| length : int
| Number of random bytes.
|
| Returns
| -------
| out : bytes
| String of length `length`.
|
| Notes
| -----
| This function generates random bytes from a discrete uniform
| distribution. The generated bytes are independent from the CPU's
| native endianness.
|
| Examples
| --------
| >>> rng = np.random.default_rng()
| >>> rng.bytes(10)
| b'\xfeC\x9b\x86\x17\xf2\xa1\xafcp' # random
|
| chisquare(self, df, size=None)
| chisquare(df, size=None)
|
| Draw samples from a chi-square distribution.
|
| When `df` independent random variables, each with standard normal
| distributions (mean 0, variance 1), are squared and summed, the
| resulting distribution is chi-square (see Notes). This distribution
| is often used in hypothesis testing.
|
| Parameters
| ----------
| df : float or array_like of floats
| Number of degrees of freedom, must be > 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``df`` is a scalar. Otherwise,
| ``np.array(df).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized chi-square distribution.
|
| Raises
| ------
| ValueError
| When `df` <= 0 or when an inappropriate `size` (e.g. ``size=-1``)
| is given.
|
| Notes
| -----
| The variable obtained by summing the squares of `df` independent,
| standard normally distributed random variables:
|
| .. math:: Q = \sum_{i=0}^{\mathtt{df}} X^2_i
|
| is chi-square distributed, denoted
|
| .. math:: Q \sim \chi^2_k.
|
| The probability density function of the chi-squared distribution is
|
| .. math:: p(x) = \frac{(1/2)^{k/2}}{\Gamma(k/2)}
| x^{k/2 - 1} e^{-x/2},
|
| where :math:`\Gamma` is the gamma function,
|
| .. math:: \Gamma(x) = \int_0^{-\infty} t^{x - 1} e^{-t} dt.
|
| References
| ----------
| .. [1] NIST "Engineering Statistics Handbook"
| https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
|
| Examples
| --------
| >>> rng = np.random.default_rng()
| >>> rng.chisquare(2,4)
| array([ 1.89920014, 9.00867716, 3.13710533, 5.62318272]) # random
|
| The distribution of a chi-square random variable
| with 20 degrees of freedom looks as follows:
|
| >>> import matplotlib.pyplot as plt
| >>> import scipy.stats as stats
| >>> s = rng.chisquare(20, 10000)
| >>> count, bins, _ = plt.hist(s, 30, density=True)
| >>> x = np.linspace(0, 60, 1000)
| >>> plt.plot(x, stats.chi2.pdf(x, df=20))
| >>> plt.xlim([0, 60])
| >>> plt.show()
|
| choice(self, a, size=None, replace=True, p=None, axis=0, shuffle=True)
| choice(a, size=None, replace=True, p=None, axis=0, shuffle=True)
|
| Generates a random sample from a given array
|
| Parameters
| ----------
| a : {array_like, int}
| If an ndarray, a random sample is generated from its elements.
| If an int, the random sample is generated from np.arange(a).
| size : {int, tuple[int]}, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn from the 1-d `a`. If `a` has more
| than one dimension, the `size` shape will be inserted into the
| `axis` dimension, so the output ``ndim`` will be ``a.ndim - 1 +
| len(size)``. Default is None, in which case a single value is
| returned.
| replace : bool, optional
| Whether the sample is with or without replacement. Default is True,
| meaning that a value of ``a`` can be selected multiple times.
| p : 1-D array_like, optional
| The probabilities associated with each entry in a.
| If not given, the sample assumes a uniform distribution over all
| entries in ``a``.
| axis : int, optional
| The axis along which the selection is performed. The default, 0,
| selects by row.
| shuffle : bool, optional
| Whether the sample is shuffled when sampling without replacement.
| Default is True, False provides a speedup.
|
| Returns
| -------
| samples : single item or ndarray
| The generated random samples
|
| Raises
| ------
| ValueError
| If a is an int and less than zero, if p is not 1-dimensional, if
| a is array-like with a size 0, if p is not a vector of
| probabilities, if a and p have different lengths, or if
| replace=False and the sample size is greater than the population
| size.
|
| See Also
| --------
| integers, shuffle, permutation
|
| Notes
| -----
| Setting user-specified probabilities through ``p`` uses a more general but less
| efficient sampler than the default. The general sampler produces a different sample
| than the optimized sampler even if each element of ``p`` is 1 / len(a).
|
| ``p`` must sum to 1 when cast to ``float64``. To ensure this, you may wish
| to normalize using ``p = p / np.sum(p, dtype=float)``.
|
| Examples
| --------
| Generate a uniform random sample from np.arange(5) of size 3:
|
| >>> rng = np.random.default_rng()
| >>> rng.choice(5, 3)
| array([0, 3, 4]) # random
| >>> #This is equivalent to rng.integers(0,5,3)
|
| Generate a non-uniform random sample from np.arange(5) of size 3:
|
| >>> rng.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
| array([3, 3, 0]) # random
|
| Generate a uniform random sample from np.arange(5) of size 3 without
| replacement:
|
| >>> rng.choice(5, 3, replace=False)
| array([3,1,0]) # random
| >>> #This is equivalent to rng.permutation(np.arange(5))[:3]
|
| Generate a uniform random sample from a 2-D array along the first
| axis (the default), without replacement:
|
| >>> rng.choice([[0, 1, 2], [3, 4, 5], [6, 7, 8]], 2, replace=False)
| array([[3, 4, 5], # random
| [0, 1, 2]])
|
| Generate a non-uniform random sample from np.arange(5) of size
| 3 without replacement:
|
| >>> rng.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
| array([2, 3, 0]) # random
|
| Any of the above can be repeated with an arbitrary array-like
| instead of just integers. For instance:
|
| >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
| >>> rng.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
| array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], # random
| dtype='<U11')
|
| dirichlet(self, alpha, size=None)
| dirichlet(alpha, size=None)
|
| Draw samples from the Dirichlet distribution.
|
| Draw `size` samples of dimension k from a Dirichlet distribution. A
| Dirichlet-distributed random variable can be seen as a multivariate
| generalization of a Beta distribution. The Dirichlet distribution
| is a conjugate prior of a multinomial distribution in Bayesian
| inference.
|
| Parameters
| ----------
| alpha : sequence of floats, length k
| Parameter of the distribution (length ``k`` for sample of
| length ``k``).
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| vector of length ``k`` is returned.
|
| Returns
| -------
| samples : ndarray,
| The drawn samples, of shape ``(size, k)``.
|
| Raises
| ------
| ValueError
| If any value in ``alpha`` is less than zero
|
| Notes
| -----
| The Dirichlet distribution is a distribution over vectors
| :math:`x` that fulfil the conditions :math:`x_i>0` and
| :math:`\sum_{i=1}^k x_i = 1`.
|
| The probability density function :math:`p` of a
| Dirichlet-distributed random vector :math:`X` is
| proportional to
|
| .. math:: p(x) \propto \prod_{i=1}^{k}{x^{\alpha_i-1}_i},
|
| where :math:`\alpha` is a vector containing the positive
| concentration parameters.
|
| The method uses the following property for computation: let :math:`Y`
| be a random vector which has components that follow a standard gamma
| distribution, then :math:`X = \frac{1}{\sum_{i=1}^k{Y_i}} Y`
| is Dirichlet-distributed
|
| References
| ----------
| .. [1] David McKay, "Information Theory, Inference and Learning
| Algorithms," chapter 23,
| https://www.inference.org.uk/mackay/itila/
| .. [2] Wikipedia, "Dirichlet distribution",
| https://en.wikipedia.org/wiki/Dirichlet_distribution
|
| Examples
| --------
| Taking an example cited in Wikipedia, this distribution can be used if
| one wanted to cut strings (each of initial length 1.0) into K pieces
| with different lengths, where each piece had, on average, a designated
| average length, but allowing some variation in the relative sizes of
| the pieces.
|
| >>> rng = np.random.default_rng()
| >>> s = rng.dirichlet((10, 5, 3), 20).transpose()
|
| >>> import matplotlib.pyplot as plt
| >>> plt.barh(range(20), s[0])
| >>> plt.barh(range(20), s[1], left=s[0], color='g')
| >>> plt.barh(range(20), s[2], left=s[0]+s[1], color='r')
| >>> plt.title("Lengths of Strings")
|
| exponential(self, scale=1.0, size=None)
| exponential(scale=1.0, size=None)
|
| Draw samples from an exponential distribution.
|
| Its probability density function is
|
| .. math:: f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}),
|
| for ``x > 0`` and 0 elsewhere. :math:`\beta` is the scale parameter,
| which is the inverse of the rate parameter :math:`\lambda = 1/\beta`.
| The rate parameter is an alternative, widely used parameterization
| of the exponential distribution [3]_.
|
| The exponential distribution is a continuous analogue of the
| geometric distribution. It describes many common situations, such as
| the size of raindrops measured over many rainstorms [1]_, or the time
| between page requests to Wikipedia [2]_.
|
| Parameters
| ----------
| scale : float or array_like of floats
| The scale parameter, :math:`\beta = 1/\lambda`. Must be
| non-negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``scale`` is a scalar. Otherwise,
| ``np.array(scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized exponential distribution.
|
| Examples
| --------
| Assume a company has 10000 customer support agents and the time
| between customer calls is exponentially distributed and that the
| average time between customer calls is 4 minutes.
|
| >>> scale, size = 4, 10000
| >>> rng = np.random.default_rng()
| >>> time_between_calls = rng.exponential(scale=scale, size=size)
|
| What is the probability that a customer will call in the next
| 4 to 5 minutes?
|
| >>> x = ((time_between_calls < 5).sum())/size
| >>> y = ((time_between_calls < 4).sum())/size
| >>> x - y
| 0.08 # may vary
|
| The corresponding distribution can be visualized as follows:
|
| >>> import matplotlib.pyplot as plt
| >>> scale, size = 4, 10000
| >>> rng = np.random.default_rng()
| >>> sample = rng.exponential(scale=scale, size=size)
| >>> count, bins, _ = plt.hist(sample, 30, density=True)
| >>> plt.plot(bins, scale**(-1)*np.exp(-scale**-1*bins), linewidth=2, color='r')
| >>> plt.show()
|
| References
| ----------
| .. [1] Peyton Z. Peebles Jr., "Probability, Random Variables and
| Random Signal Principles", 4th ed, 2001, p. 57.
| .. [2] Wikipedia, "Poisson process",
| https://en.wikipedia.org/wiki/Poisson_process
| .. [3] Wikipedia, "Exponential distribution",
| https://en.wikipedia.org/wiki/Exponential_distribution
|
| f(self, dfnum, dfden, size=None)
| f(dfnum, dfden, size=None)
|
| Draw samples from an F distribution.
|
| Samples are drawn from an F distribution with specified parameters,
| `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of
| freedom in denominator), where both parameters must be greater than
| zero.
|
| The random variate of the F distribution (also known as the
| Fisher distribution) is a continuous probability distribution
| that arises in ANOVA tests, and is the ratio of two chi-square
| variates.
|
| Parameters
| ----------
| dfnum : float or array_like of floats
| Degrees of freedom in numerator, must be > 0.
| dfden : float or array_like of float
| Degrees of freedom in denominator, must be > 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``dfnum`` and ``dfden`` are both scalars.
| Otherwise, ``np.broadcast(dfnum, dfden).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Fisher distribution.
|
| See Also
| --------
| scipy.stats.f : probability density function, distribution or
| cumulative density function, etc.
|
| Notes
| -----
| The F statistic is used to compare in-group variances to between-group
| variances. Calculating the distribution depends on the sampling, and
| so it is a function of the respective degrees of freedom in the
| problem. The variable `dfnum` is the number of samples minus one, the
| between-groups degrees of freedom, while `dfden` is the within-groups
| degrees of freedom, the sum of the number of samples in each group
| minus the number of groups.
|
| References
| ----------
| .. [1] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
| Fifth Edition, 2002.
| .. [2] Wikipedia, "F-distribution",
| https://en.wikipedia.org/wiki/F-distribution
|
| Examples
| --------
| An example from Glantz[1], pp 47-40:
|
| Two groups, children of diabetics (25 people) and children from people
| without diabetes (25 controls). Fasting blood glucose was measured,
| case group had a mean value of 86.1, controls had a mean value of
| 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these
| data consistent with the null hypothesis that the parents diabetic
| status does not affect their children's blood glucose levels?
| Calculating the F statistic from the data gives a value of 36.01.
|
| Draw samples from the distribution:
|
| >>> dfnum = 1. # between group degrees of freedom
| >>> dfden = 48. # within groups degrees of freedom
| >>> rng = np.random.default_rng()
| >>> s = rng.f(dfnum, dfden, 1000)
|
| The lower bound for the top 1% of the samples is :
|
| >>> np.sort(s)[-10]
| 7.61988120985 # random
|
| So there is about a 1% chance that the F statistic will exceed 7.62,
| the measured value is 36, so the null hypothesis is rejected at the 1%
| level.
|
| The corresponding probability density function for ``n = 20``
| and ``m = 20`` is:
|
| >>> import matplotlib.pyplot as plt
| >>> from scipy import stats
| >>> dfnum, dfden, size = 20, 20, 10000
| >>> s = rng.f(dfnum=dfnum, dfden=dfden, size=size)
| >>> bins, density, _ = plt.hist(s, 30, density=True)
| >>> x = np.linspace(0, 5, 1000)
| >>> plt.plot(x, stats.f.pdf(x, dfnum, dfden))
| >>> plt.xlim([0, 5])
| >>> plt.show()
|
| gamma(self, shape, scale=1.0, size=None)
| gamma(shape, scale=1.0, size=None)
|
| Draw samples from a Gamma distribution.
|
| Samples are drawn from a Gamma distribution with specified parameters,
| `shape` (sometimes designated "k") and `scale` (sometimes designated
| "theta"), where both parameters are > 0.
|
| Parameters
| ----------
| shape : float or array_like of floats
| The shape of the gamma distribution. Must be non-negative.
| scale : float or array_like of floats, optional
| The scale of the gamma distribution. Must be non-negative.
| Default is equal to 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``shape`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(shape, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized gamma distribution.
|
| See Also
| --------
| scipy.stats.gamma : probability density function, distribution or
| cumulative density function, etc.
|
| Notes
| -----
| The probability density for the Gamma distribution is
|
| .. math:: p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},
|
| where :math:`k` is the shape and :math:`\theta` the scale,
| and :math:`\Gamma` is the Gamma function.
|
| The Gamma distribution is often used to model the times to failure of
| electronic components, and arises naturally in processes for which the
| waiting times between Poisson distributed events are relevant.
|
| References
| ----------
| .. [1] Weisstein, Eric W. "Gamma Distribution." From MathWorld--A
| Wolfram Web Resource.
| https://mathworld.wolfram.com/GammaDistribution.html
| .. [2] Wikipedia, "Gamma distribution",
| https://en.wikipedia.org/wiki/Gamma_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> shape, scale = 2., 2. # mean=4, std=2*sqrt(2)
| >>> rng = np.random.default_rng()
| >>> s = rng.gamma(shape, scale, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> import scipy.special as sps # doctest: +SKIP
| >>> count, bins, _ = plt.hist(s, 50, density=True)
| >>> y = bins**(shape-1)*(np.exp(-bins/scale) / # doctest: +SKIP
| ... (sps.gamma(shape)*scale**shape))
| >>> plt.plot(bins, y, linewidth=2, color='r') # doctest: +SKIP
| >>> plt.show()
|
| geometric(self, p, size=None)
| geometric(p, size=None)
|
| Draw samples from the geometric distribution.
|
| Bernoulli trials are experiments with one of two outcomes:
| success or failure (an example of such an experiment is flipping
| a coin). The geometric distribution models the number of trials
| that must be run in order to achieve success. It is therefore
| supported on the positive integers, ``k = 1, 2, ...``.
|
| The probability mass function of the geometric distribution is
|
| .. math:: f(k) = (1 - p)^{k - 1} p
|
| where `p` is the probability of success of an individual trial.
|
| Parameters
| ----------
| p : float or array_like of floats
| The probability of success of an individual trial.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``p`` is a scalar. Otherwise,
| ``np.array(p).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized geometric distribution.
|
| References
| ----------
|
| .. [1] Wikipedia, "Geometric distribution",
| https://en.wikipedia.org/wiki/Geometric_distribution
|
| Examples
| --------
| Draw 10,000 values from the geometric distribution, with the
| probability of an individual success equal to ``p = 0.35``:
|
| >>> p, size = 0.35, 10000
| >>> rng = np.random.default_rng()
| >>> sample = rng.geometric(p=p, size=size)
|
| What proportion of trials succeeded after a single run?
|
| >>> (sample == 1).sum()/size
| 0.34889999999999999 # may vary
|
| The geometric distribution with ``p=0.35`` looks as follows:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, _ = plt.hist(sample, bins=30, density=True)
| >>> plt.plot(bins, (1-p)**(bins-1)*p)
| >>> plt.xlim([0, 25])
| >>> plt.show()
|
| gumbel(self, loc=0.0, scale=1.0, size=None)
| gumbel(loc=0.0, scale=1.0, size=None)
|
| Draw samples from a Gumbel distribution.
|
| Draw samples from a Gumbel distribution with specified location and
| scale. For more information on the Gumbel distribution, see
| Notes and References below.
|
| Parameters
| ----------
| loc : float or array_like of floats, optional
| The location of the mode of the distribution. Default is 0.
| scale : float or array_like of floats, optional
| The scale parameter of the distribution. Default is 1. Must be non-
| negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``loc`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Gumbel distribution.
|
| See Also
| --------
| scipy.stats.gumbel_l
| scipy.stats.gumbel_r
| scipy.stats.genextreme
| weibull
|
| Notes
| -----
| The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme
| Value Type I) distribution is one of a class of Generalized Extreme
| Value (GEV) distributions used in modeling extreme value problems.
| The Gumbel is a special case of the Extreme Value Type I distribution
| for maximums from distributions with "exponential-like" tails.
|
| The probability density for the Gumbel distribution is
|
| .. math:: p(x) = \frac{e^{-(x - \mu)/ \beta}}{\beta} e^{ -e^{-(x - \mu)/
| \beta}},
|
| where :math:`\mu` is the mode, a location parameter, and
| :math:`\beta` is the scale parameter.
|
| The Gumbel (named for German mathematician Emil Julius Gumbel) was used
| very early in the hydrology literature, for modeling the occurrence of
| flood events. It is also used for modeling maximum wind speed and
| rainfall rates. It is a "fat-tailed" distribution - the probability of
| an event in the tail of the distribution is larger than if one used a
| Gaussian, hence the surprisingly frequent occurrence of 100-year
| floods. Floods were initially modeled as a Gaussian process, which
| underestimated the frequency of extreme events.
|
| It is one of a class of extreme value distributions, the Generalized
| Extreme Value (GEV) distributions, which also includes the Weibull and
| Frechet.
|
| The function has a mean of :math:`\mu + 0.57721\beta` and a variance
| of :math:`\frac{\pi^2}{6}\beta^2`.
|
| References
| ----------
| .. [1] Gumbel, E. J., "Statistics of Extremes,"
| New York: Columbia University Press, 1958.
| .. [2] Reiss, R.-D. and Thomas, M., "Statistical Analysis of Extreme
| Values from Insurance, Finance, Hydrology and Other Fields,"
| Basel: Birkhauser Verlag, 2001.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> rng = np.random.default_rng()
| >>> mu, beta = 0, 0.1 # location and scale
| >>> s = rng.gumbel(mu, beta, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, _ = plt.hist(s, 30, density=True)
| >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
| ... * np.exp( -np.exp( -(bins - mu) /beta) ),
| ... linewidth=2, color='r')
| >>> plt.show()
|
| Show how an extreme value distribution can arise from a Gaussian process
| and compare to a Gaussian:
|
| >>> means = []
| >>> maxima = []
| >>> for i in range(0,1000) :
| ... a = rng.normal(mu, beta, 1000)
| ... means.append(a.mean())
| ... maxima.append(a.max())
| >>> count, bins, _ = plt.hist(maxima, 30, density=True)
| >>> beta = np.std(maxima) * np.sqrt(6) / np.pi
| >>> mu = np.mean(maxima) - 0.57721*beta
| >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
| ... * np.exp(-np.exp(-(bins - mu)/beta)),
| ... linewidth=2, color='r')
| >>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi))
| ... * np.exp(-(bins - mu)**2 / (2 * beta**2)),
| ... linewidth=2, color='g')
| >>> plt.show()
|
| hypergeometric(self, ngood, nbad, nsample, size=None)
| hypergeometric(ngood, nbad, nsample, size=None)
|
| Draw samples from a Hypergeometric distribution.
|
| Samples are drawn from a hypergeometric distribution with specified
| parameters, `ngood` (ways to make a good selection), `nbad` (ways to make
| a bad selection), and `nsample` (number of items sampled, which is less
| than or equal to the sum ``ngood + nbad``).
|
| Parameters
| ----------
| ngood : int or array_like of ints
| Number of ways to make a good selection. Must be nonnegative and
| less than 10**9.
| nbad : int or array_like of ints
| Number of ways to make a bad selection. Must be nonnegative and
| less than 10**9.
| nsample : int or array_like of ints
| Number of items sampled. Must be nonnegative and less than
| ``ngood + nbad``.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if `ngood`, `nbad`, and `nsample`
| are all scalars. Otherwise, ``np.broadcast(ngood, nbad, nsample).size``
| samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized hypergeometric distribution. Each
| sample is the number of good items within a randomly selected subset of
| size `nsample` taken from a set of `ngood` good items and `nbad` bad items.
|
| See Also
| --------
| multivariate_hypergeometric : Draw samples from the multivariate
| hypergeometric distribution.
| scipy.stats.hypergeom : probability density function, distribution or
| cumulative density function, etc.
|
| Notes
| -----
| The probability density for the Hypergeometric distribution is
|
| .. math:: P(x) = \frac{\binom{g}{x}\binom{b}{n-x}}{\binom{g+b}{n}},
|
| where :math:`0 \le x \le n` and :math:`n-b \le x \le g`
|
| for P(x) the probability of ``x`` good results in the drawn sample,
| g = `ngood`, b = `nbad`, and n = `nsample`.
|
| Consider an urn with black and white marbles in it, `ngood` of them
| are black and `nbad` are white. If you draw `nsample` balls without
| replacement, then the hypergeometric distribution describes the
| distribution of black balls in the drawn sample.
|
| Note that this distribution is very similar to the binomial
| distribution, except that in this case, samples are drawn without
| replacement, whereas in the Binomial case samples are drawn with
| replacement (or the sample space is infinite). As the sample space
| becomes large, this distribution approaches the binomial.
|
| The arguments `ngood` and `nbad` each must be less than `10**9`. For
| extremely large arguments, the algorithm that is used to compute the
| samples [4]_ breaks down because of loss of precision in floating point
| calculations. For such large values, if `nsample` is not also large,
| the distribution can be approximated with the binomial distribution,
| `binomial(n=nsample, p=ngood/(ngood + nbad))`.
|
| References
| ----------
| .. [1] Lentner, Marvin, "Elementary Applied Statistics", Bogden
| and Quigley, 1972.
| .. [2] Weisstein, Eric W. "Hypergeometric Distribution." From
| MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/HypergeometricDistribution.html
| .. [3] Wikipedia, "Hypergeometric distribution",
| https://en.wikipedia.org/wiki/Hypergeometric_distribution
| .. [4] Stadlober, Ernst, "The ratio of uniforms approach for generating
| discrete random variates", Journal of Computational and Applied
| Mathematics, 31, pp. 181-189 (1990).
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> rng = np.random.default_rng()
| >>> ngood, nbad, nsamp = 100, 2, 10
| # number of good, number of bad, and number of samples
| >>> s = rng.hypergeometric(ngood, nbad, nsamp, 1000)
| >>> from matplotlib.pyplot import hist
| >>> hist(s)
| # note that it is very unlikely to grab both bad items
|
| Suppose you have an urn with 15 white and 15 black marbles.
| If you pull 15 marbles at random, how likely is it that
| 12 or more of them are one color?
|
| >>> s = rng.hypergeometric(15, 15, 15, 100000)
| >>> sum(s>=12)/100000. + sum(s<=3)/100000.
| # answer = 0.003 ... pretty unlikely!
|
| integers(self, low, high=None, size=None, dtype=<class 'numpy.int64'>, endpoint=False)
| integers(low, high=None, size=None, dtype=np.int64, endpoint=False)
|
| Return random integers from `low` (inclusive) to `high` (exclusive), or
| if endpoint=True, `low` (inclusive) to `high` (inclusive). Replaces
| `RandomState.randint` (with endpoint=False) and
| `RandomState.random_integers` (with endpoint=True)
|
| Return random integers from the "discrete uniform" distribution of
| the specified dtype. If `high` is None (the default), then results are
| from 0 to `low`.
|
| Parameters
| ----------
| low : int or array-like of ints
| Lowest (signed) integers to be drawn from the distribution (unless
| ``high=None``, in which case this parameter is 0 and this value is
| used for `high`).
| high : int or array-like of ints, optional
| If provided, one above the largest (signed) integer to be drawn
| from the distribution (see above for behavior if ``high=None``).
| If array-like, must contain integer values
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| dtype : dtype, optional
| Desired dtype of the result. Byteorder must be native.
| The default value is np.int64.
| endpoint : bool, optional
| If true, sample from the interval [low, high] instead of the
| default [low, high)
| Defaults to False
|
| Returns
| -------
| out : int or ndarray of ints
| `size`-shaped array of random integers from the appropriate
| distribution, or a single such random int if `size` not provided.
|
| Notes
| -----
| When using broadcasting with uint64 dtypes, the maximum value (2**64)
| cannot be represented as a standard integer type. The high array (or
| low if high is None) must have object dtype, e.g., array([2**64]).
|
| Examples
| --------
| >>> rng = np.random.default_rng()
| >>> rng.integers(2, size=10)
| array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) # random
| >>> rng.integers(1, size=10)
| array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
|
| Generate a 2 x 4 array of ints between 0 and 4, inclusive:
|
| >>> rng.integers(5, size=(2, 4))
| array([[4, 0, 2, 1],
| [3, 2, 2, 0]]) # random
|
| Generate a 1 x 3 array with 3 different upper bounds
|
| >>> rng.integers(1, [3, 5, 10])
| array([2, 2, 9]) # random
|
| Generate a 1 by 3 array with 3 different lower bounds
|
| >>> rng.integers([1, 5, 7], 10)
| array([9, 8, 7]) # random
|
| Generate a 2 by 4 array using broadcasting with dtype of uint8
|
| >>> rng.integers([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
| array([[ 8, 6, 9, 7],
| [ 1, 16, 9, 12]], dtype=uint8) # random
|
| References
| ----------
| .. [1] Daniel Lemire., "Fast Random Integer Generation in an Interval",
| ACM Transactions on Modeling and Computer Simulation 29 (1), 2019,
| https://arxiv.org/abs/1805.10941.
|
| laplace(self, loc=0.0, scale=1.0, size=None)
| laplace(loc=0.0, scale=1.0, size=None)
|
| Draw samples from the Laplace or double exponential distribution with
| specified location (or mean) and scale (decay).
|
| The Laplace distribution is similar to the Gaussian/normal distribution,
| but is sharper at the peak and has fatter tails. It represents the
| difference between two independent, identically distributed exponential
| random variables.
|
| Parameters
| ----------
| loc : float or array_like of floats, optional
| The position, :math:`\mu`, of the distribution peak. Default is 0.
| scale : float or array_like of floats, optional
| :math:`\lambda`, the exponential decay. Default is 1. Must be non-
| negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``loc`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Laplace distribution.
|
| Notes
| -----
| It has the probability density function
|
| .. math:: f(x; \mu, \lambda) = \frac{1}{2\lambda}
| \exp\left(-\frac{|x - \mu|}{\lambda}\right).
|
| The first law of Laplace, from 1774, states that the frequency
| of an error can be expressed as an exponential function of the
| absolute magnitude of the error, which leads to the Laplace
| distribution. For many problems in economics and health
| sciences, this distribution seems to model the data better
| than the standard Gaussian distribution.
|
| References
| ----------
| .. [1] Abramowitz, M. and Stegun, I. A. (Eds.). "Handbook of
| Mathematical Functions with Formulas, Graphs, and Mathematical
| Tables, 9th printing," New York: Dover, 1972.
| .. [2] Kotz, Samuel, et. al. "The Laplace Distribution and
| Generalizations, " Birkhauser, 2001.
| .. [3] Weisstein, Eric W. "Laplace Distribution."
| From MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/LaplaceDistribution.html
| .. [4] Wikipedia, "Laplace distribution",
| https://en.wikipedia.org/wiki/Laplace_distribution
|
| Examples
| --------
| Draw samples from the distribution
|
| >>> loc, scale = 0., 1.
| >>> rng = np.random.default_rng()
| >>> s = rng.laplace(loc, scale, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, _ = plt.hist(s, 30, density=True)
| >>> x = np.arange(-8., 8., .01)
| >>> pdf = np.exp(-abs(x-loc)/scale)/(2.*scale)
| >>> plt.plot(x, pdf)
|
| Plot Gaussian for comparison:
|
| >>> g = (1/(scale * np.sqrt(2 * np.pi)) *
| ... np.exp(-(x - loc)**2 / (2 * scale**2)))
| >>> plt.plot(x,g)
|
| logistic(self, loc=0.0, scale=1.0, size=None)
| logistic(loc=0.0, scale=1.0, size=None)
|
| Draw samples from a logistic distribution.
|
| Samples are drawn from a logistic distribution with specified
| parameters, loc (location or mean, also median), and scale (>0).
|
| Parameters
| ----------
| loc : float or array_like of floats, optional
| Parameter of the distribution. Default is 0.
| scale : float or array_like of floats, optional
| Parameter of the distribution. Must be non-negative.
| Default is 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``loc`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized logistic distribution.
|
| See Also
| --------
| scipy.stats.logistic : probability density function, distribution or
| cumulative density function, etc.
|
| Notes
| -----
| The probability density for the Logistic distribution is
|
| .. math:: P(x) = \frac{e^{-(x-\mu)/s}}{s(1+e^{-(x-\mu)/s})^2},
|
| where :math:`\mu` = location and :math:`s` = scale.
|
| The Logistic distribution is used in Extreme Value problems where it
| can act as a mixture of Gumbel distributions, in Epidemiology, and by
| the World Chess Federation (FIDE) where it is used in the Elo ranking
| system, assuming the performance of each player is a logistically
| distributed random variable.
|
| References
| ----------
| .. [1] Reiss, R.-D. and Thomas M. (2001), "Statistical Analysis of
| Extreme Values, from Insurance, Finance, Hydrology and Other
| Fields," Birkhauser Verlag, Basel, pp 132-133.
| .. [2] Weisstein, Eric W. "Logistic Distribution." From
| MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/LogisticDistribution.html
| .. [3] Wikipedia, "Logistic-distribution",
| https://en.wikipedia.org/wiki/Logistic_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> loc, scale = 10, 1
| >>> rng = np.random.default_rng()
| >>> s = rng.logistic(loc, scale, 10000)
| >>> import matplotlib.pyplot as plt
| >>> count, bins, _ = plt.hist(s, bins=50, label='Sampled data')
|
| # plot sampled data against the exact distribution
|
| >>> def logistic(x, loc, scale):
| ... return np.exp((loc-x)/scale)/(scale*(1+np.exp((loc-x)/scale))**2)
| >>> logistic_values = logistic(bins, loc, scale)
| >>> bin_spacing = np.mean(np.diff(bins))
| >>> plt.plot(bins, logistic_values * bin_spacing * s.size, label='Logistic PDF')
| >>> plt.legend()
| >>> plt.show()
|
| lognormal(self, mean=0.0, sigma=1.0, size=None)
| lognormal(mean=0.0, sigma=1.0, size=None)
|
| Draw samples from a log-normal distribution.
|
| Draw samples from a log-normal distribution with specified mean,
| standard deviation, and array shape. Note that the mean and standard
| deviation are not the values for the distribution itself, but of the
| underlying normal distribution it is derived from.
|
| Parameters
| ----------
| mean : float or array_like of floats, optional
| Mean value of the underlying normal distribution. Default is 0.
| sigma : float or array_like of floats, optional
| Standard deviation of the underlying normal distribution. Must be
| non-negative. Default is 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``mean`` and ``sigma`` are both scalars.
| Otherwise, ``np.broadcast(mean, sigma).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized log-normal distribution.
|
| See Also
| --------
| scipy.stats.lognorm : probability density function, distribution,
| cumulative density function, etc.
|
| Notes
| -----
| A variable `x` has a log-normal distribution if `log(x)` is normally
| distributed. The probability density function for the log-normal
| distribution is:
|
| .. math:: p(x) = \frac{1}{\sigma x \sqrt{2\pi}}
| e^{(-\frac{(ln(x)-\mu)^2}{2\sigma^2})}
|
| where :math:`\mu` is the mean and :math:`\sigma` is the standard
| deviation of the normally distributed logarithm of the variable.
| A log-normal distribution results if a random variable is the *product*
| of a large number of independent, identically-distributed variables in
| the same way that a normal distribution results if the variable is the
| *sum* of a large number of independent, identically-distributed
| variables.
|
| References
| ----------
| .. [1] Limpert, E., Stahel, W. A., and Abbt, M., "Log-normal
| Distributions across the Sciences: Keys and Clues,"
| BioScience, Vol. 51, No. 5, May, 2001.
| https://stat.ethz.ch/~stahel/lognormal/bioscience.pdf
| .. [2] Reiss, R.D. and Thomas, M., "Statistical Analysis of Extreme
| Values," Basel: Birkhauser Verlag, 2001, pp. 31-32.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> rng = np.random.default_rng()
| >>> mu, sigma = 3., 1. # mean and standard deviation
| >>> s = rng.lognormal(mu, sigma, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, _ = plt.hist(s, 100, density=True, align='mid')
|
| >>> x = np.linspace(min(bins), max(bins), 10000)
| >>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
| ... / (x * sigma * np.sqrt(2 * np.pi)))
|
| >>> plt.plot(x, pdf, linewidth=2, color='r')
| >>> plt.axis('tight')
| >>> plt.show()
|
| Demonstrate that taking the products of random samples from a uniform
| distribution can be fit well by a log-normal probability density
| function.
|
| >>> # Generate a thousand samples: each is the product of 100 random
| >>> # values, drawn from a normal distribution.
| >>> rng = rng
| >>> b = []
| >>> for i in range(1000):
| ... a = 10. + rng.standard_normal(100)
| ... b.append(np.prod(a))
|
| >>> b = np.array(b) / np.min(b) # scale values to be positive
| >>> count, bins, _ = plt.hist(b, 100, density=True, align='mid')
| >>> sigma = np.std(np.log(b))
| >>> mu = np.mean(np.log(b))
|
| >>> x = np.linspace(min(bins), max(bins), 10000)
| >>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
| ... / (x * sigma * np.sqrt(2 * np.pi)))
|
| >>> plt.plot(x, pdf, color='r', linewidth=2)
| >>> plt.show()
|
| logseries(self, p, size=None)
| logseries(p, size=None)
|
| Draw samples from a logarithmic series distribution.
|
| Samples are drawn from a log series distribution with specified
| shape parameter, 0 <= ``p`` < 1.
|
| Parameters
| ----------
| p : float or array_like of floats
| Shape parameter for the distribution. Must be in the range [0, 1).
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``p`` is a scalar. Otherwise,
| ``np.array(p).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized logarithmic series distribution.
|
| See Also
| --------
| scipy.stats.logser : probability density function, distribution or
| cumulative density function, etc.
|
| Notes
| -----
| The probability mass function for the Log Series distribution is
|
| .. math:: P(k) = \frac{-p^k}{k \ln(1-p)},
|
| where p = probability.
|
| The log series distribution is frequently used to represent species
| richness and occurrence, first proposed by Fisher, Corbet, and
| Williams in 1943 [2]. It may also be used to model the numbers of
| occupants seen in cars [3].
|
| References
| ----------
| .. [1] Buzas, Martin A.; Culver, Stephen J., Understanding regional
| species diversity through the log series distribution of
| occurrences: BIODIVERSITY RESEARCH Diversity & Distributions,
| Volume 5, Number 5, September 1999 , pp. 187-195(9).
| .. [2] Fisher, R.A,, A.S. Corbet, and C.B. Williams. 1943. The
| relation between the number of species and the number of
| individuals in a random sample of an animal population.
| Journal of Animal Ecology, 12:42-58.
| .. [3] D. J. Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small
| Data Sets, CRC Press, 1994.
| .. [4] Wikipedia, "Logarithmic distribution",
| https://en.wikipedia.org/wiki/Logarithmic_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> a = .6
| >>> rng = np.random.default_rng()
| >>> s = rng.logseries(a, 10000)
| >>> import matplotlib.pyplot as plt
| >>> bins = np.arange(-.5, max(s) + .5 )
| >>> count, bins, _ = plt.hist(s, bins=bins, label='Sample count')
|
| # plot against distribution
|
| >>> def logseries(k, p):
| ... return -p**k/(k*np.log(1-p))
| >>> centres = np.arange(1, max(s) + 1)
| >>> plt.plot(centres, logseries(centres, a) * s.size, 'r', label='logseries PMF')
| >>> plt.legend()
| >>> plt.show()
|
| multinomial(self, n, pvals, size=None)
| multinomial(n, pvals, size=None)
|
| Draw samples from a multinomial distribution.
|
| The multinomial distribution is a multivariate generalization of the
| binomial distribution. Take an experiment with one of ``p``
| possible outcomes. An example of such an experiment is throwing a dice,
| where the outcome can be 1 through 6. Each sample drawn from the
| distribution represents `n` such experiments. Its values,
| ``X_i = [X_0, X_1, ..., X_p]``, represent the number of times the
| outcome was ``i``.
|
| Parameters
| ----------
| n : int or array-like of ints
| Number of experiments.
| pvals : array-like of floats
| Probabilities of each of the ``p`` different outcomes with shape
| ``(k0, k1, ..., kn, p)``. Each element ``pvals[i,j,...,:]`` must
| sum to 1 (however, the last element is always assumed to account
| for the remaining probability, as long as
| ``sum(pvals[..., :-1], axis=-1) <= 1.0``. Must have at least 1
| dimension where pvals.shape[-1] > 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn each with ``p`` elements. Default
| is None where the output size is determined by the broadcast shape
| of ``n`` and all by the final dimension of ``pvals``, which is
| denoted as ``b=(b0, b1, ..., bq)``. If size is not None, then it
| must be compatible with the broadcast shape ``b``. Specifically,
| size must have ``q`` or more elements and size[-(q-j):] must equal
| ``bj``.
|
| Returns
| -------
| out : ndarray
| The drawn samples, of shape size, if provided. When size is
| provided, the output shape is size + (p,) If not specified,
| the shape is determined by the broadcast shape of ``n`` and
| ``pvals``, ``(b0, b1, ..., bq)`` augmented with the dimension of
| the multinomial, ``p``, so that that output shape is
| ``(b0, b1, ..., bq, p)``.
|
| Each entry ``out[i,j,...,:]`` is a ``p``-dimensional value drawn
| from the distribution.
|
| .. versionchanged:: 1.22.0
| Added support for broadcasting `pvals` against `n`
|
| Examples
| --------
| Throw a dice 20 times:
|
| >>> rng = np.random.default_rng()
| >>> rng.multinomial(20, [1/6.]*6, size=1)
| array([[4, 1, 7, 5, 2, 1]]) # random
|
| It landed 4 times on 1, once on 2, etc.
|
| Now, throw the dice 20 times, and 20 times again:
|
| >>> rng.multinomial(20, [1/6.]*6, size=2)
| array([[3, 4, 3, 3, 4, 3],
| [2, 4, 3, 4, 0, 7]]) # random
|
| For the first run, we threw 3 times 1, 4 times 2, etc. For the second,
| we threw 2 times 1, 4 times 2, etc.
|
| Now, do one experiment throwing the dice 10 time, and 10 times again,
| and another throwing the dice 20 times, and 20 times again:
|
| >>> rng.multinomial([[10], [20]], [1/6.]*6, size=(2, 2))
| array([[[2, 4, 0, 1, 2, 1],
| [1, 3, 0, 3, 1, 2]],
| [[1, 4, 4, 4, 4, 3],
| [3, 3, 2, 5, 5, 2]]]) # random
|
| The first array shows the outcomes of throwing the dice 10 times, and
| the second shows the outcomes from throwing the dice 20 times.
|
| A loaded die is more likely to land on number 6:
|
| >>> rng.multinomial(100, [1/7.]*5 + [2/7.])
| array([11, 16, 14, 17, 16, 26]) # random
|
| Simulate 10 throws of a 4-sided die and 20 throws of a 6-sided die
|
| >>> rng.multinomial([10, 20],[[1/4]*4 + [0]*2, [1/6]*6])
| array([[2, 1, 4, 3, 0, 0],
| [3, 3, 3, 6, 1, 4]], dtype=int64) # random
|
| Generate categorical random variates from two categories where the
| first has 3 outcomes and the second has 2.
|
| >>> rng.multinomial(1, [[.1, .5, .4 ], [.3, .7, .0]])
| array([[0, 0, 1],
| [0, 1, 0]], dtype=int64) # random
|
| ``argmax(axis=-1)`` is then used to return the categories.
|
| >>> pvals = [[.1, .5, .4 ], [.3, .7, .0]]
| >>> rvs = rng.multinomial(1, pvals, size=(4,2))
| >>> rvs.argmax(axis=-1)
| array([[0, 1],
| [2, 0],
| [2, 1],
| [2, 0]], dtype=int64) # random
|
| The same output dimension can be produced using broadcasting.
|
| >>> rvs = rng.multinomial([[1]] * 4, pvals)
| >>> rvs.argmax(axis=-1)
| array([[0, 1],
| [2, 0],
| [2, 1],
| [2, 0]], dtype=int64) # random
|
| The probability inputs should be normalized. As an implementation
| detail, the value of the last entry is ignored and assumed to take
| up any leftover probability mass, but this should not be relied on.
| A biased coin which has twice as much weight on one side as on the
| other should be sampled like so:
|
| >>> rng.multinomial(100, [1.0 / 3, 2.0 / 3]) # RIGHT
| array([38, 62]) # random
|
| not like:
|
| >>> rng.multinomial(100, [1.0, 2.0]) # WRONG
| Traceback (most recent call last):
| ValueError: pvals < 0, pvals > 1 or pvals contains NaNs
|
| multivariate_hypergeometric(self, colors, nsample, size=None, method='marginals')
| multivariate_hypergeometric(colors, nsample, size=None,
| method='marginals')
|
| Generate variates from a multivariate hypergeometric distribution.
|
| The multivariate hypergeometric distribution is a generalization
| of the hypergeometric distribution.
|
| Choose ``nsample`` items at random without replacement from a
| collection with ``N`` distinct types. ``N`` is the length of
| ``colors``, and the values in ``colors`` are the number of occurrences
| of that type in the collection. The total number of items in the
| collection is ``sum(colors)``. Each random variate generated by this
| function is a vector of length ``N`` holding the counts of the
| different types that occurred in the ``nsample`` items.
|
| The name ``colors`` comes from a common description of the
| distribution: it is the probability distribution of the number of
| marbles of each color selected without replacement from an urn
| containing marbles of different colors; ``colors[i]`` is the number
| of marbles in the urn with color ``i``.
|
| Parameters
| ----------
| colors : sequence of integers
| The number of each type of item in the collection from which
| a sample is drawn. The values in ``colors`` must be nonnegative.
| To avoid loss of precision in the algorithm, ``sum(colors)``
| must be less than ``10**9`` when `method` is "marginals".
| nsample : int
| The number of items selected. ``nsample`` must not be greater
| than ``sum(colors)``.
| size : int or tuple of ints, optional
| The number of variates to generate, either an integer or a tuple
| holding the shape of the array of variates. If the given size is,
| e.g., ``(k, m)``, then ``k * m`` variates are drawn, where one
| variate is a vector of length ``len(colors)``, and the return value
| has shape ``(k, m, len(colors))``. If `size` is an integer, the
| output has shape ``(size, len(colors))``. Default is None, in
| which case a single variate is returned as an array with shape
| ``(len(colors),)``.
| method : string, optional
| Specify the algorithm that is used to generate the variates.
| Must be 'count' or 'marginals' (the default). See the Notes
| for a description of the methods.
|
| Returns
| -------
| variates : ndarray
| Array of variates drawn from the multivariate hypergeometric
| distribution.
|
| See Also
| --------
| hypergeometric : Draw samples from the (univariate) hypergeometric
| distribution.
|
| Notes
| -----
| The two methods do not return the same sequence of variates.
|
| The "count" algorithm is roughly equivalent to the following numpy
| code::
|
| choices = np.repeat(np.arange(len(colors)), colors)
| selection = np.random.choice(choices, nsample, replace=False)
| variate = np.bincount(selection, minlength=len(colors))
|
| The "count" algorithm uses a temporary array of integers with length
| ``sum(colors)``.
|
| The "marginals" algorithm generates a variate by using repeated
| calls to the univariate hypergeometric sampler. It is roughly
| equivalent to::
|
| variate = np.zeros(len(colors), dtype=np.int64)
| # `remaining` is the cumulative sum of `colors` from the last
| # element to the first; e.g. if `colors` is [3, 1, 5], then
| # `remaining` is [9, 6, 5].
| remaining = np.cumsum(colors[::-1])[::-1]
| for i in range(len(colors)-1):
| if nsample < 1:
| break
| variate[i] = hypergeometric(colors[i], remaining[i+1],
| nsample)
| nsample -= variate[i]
| variate[-1] = nsample
|
| The default method is "marginals". For some cases (e.g. when
| `colors` contains relatively small integers), the "count" method
| can be significantly faster than the "marginals" method. If
| performance of the algorithm is important, test the two methods
| with typical inputs to decide which works best.
|
| .. versionadded:: 1.18.0
|
| Examples
| --------
| >>> colors = [16, 8, 4]
| >>> seed = 4861946401452
| >>> gen = np.random.Generator(np.random.PCG64(seed))
| >>> gen.multivariate_hypergeometric(colors, 6)
| array([5, 0, 1])
| >>> gen.multivariate_hypergeometric(colors, 6, size=3)
| array([[5, 0, 1],
| [2, 2, 2],
| [3, 3, 0]])
| >>> gen.multivariate_hypergeometric(colors, 6, size=(2, 2))
| array([[[3, 2, 1],
| [3, 2, 1]],
| [[4, 1, 1],
| [3, 2, 1]]])
|
| multivariate_normal(self, mean, cov, size=None, check_valid='warn', tol=1e-08, *, method='svd')
| multivariate_normal(mean, cov, size=None, check_valid='warn',
| tol=1e-8, *, method='svd')
|
| Draw random samples from a multivariate normal distribution.
|
| The multivariate normal, multinormal or Gaussian distribution is a
| generalization of the one-dimensional normal distribution to higher
| dimensions. Such a distribution is specified by its mean and
| covariance matrix. These parameters are analogous to the mean
| (average or "center") and variance (the squared standard deviation,
| or "width") of the one-dimensional normal distribution.
|
| Parameters
| ----------
| mean : 1-D array_like, of length N
| Mean of the N-dimensional distribution.
| cov : 2-D array_like, of shape (N, N)
| Covariance matrix of the distribution. It must be symmetric and
| positive-semidefinite for proper sampling.
| size : int or tuple of ints, optional
| Given a shape of, for example, ``(m,n,k)``, ``m*n*k`` samples are
| generated, and packed in an `m`-by-`n`-by-`k` arrangement. Because
| each sample is `N`-dimensional, the output shape is ``(m,n,k,N)``.
| If no shape is specified, a single (`N`-D) sample is returned.
| check_valid : { 'warn', 'raise', 'ignore' }, optional
| Behavior when the covariance matrix is not positive semidefinite.
| tol : float, optional
| Tolerance when checking the singular values in covariance matrix.
| cov is cast to double before the check.
| method : { 'svd', 'eigh', 'cholesky'}, optional
| The cov input is used to compute a factor matrix A such that
| ``A @ A.T = cov``. This argument is used to select the method
| used to compute the factor matrix A. The default method 'svd' is
| the slowest, while 'cholesky' is the fastest but less robust than
| the slowest method. The method `eigh` uses eigen decomposition to
| compute A and is faster than svd but slower than cholesky.
|
| .. versionadded:: 1.18.0
|
| Returns
| -------
| out : ndarray
| The drawn samples, of shape *size*, if that was provided. If not,
| the shape is ``(N,)``.
|
| In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
| value drawn from the distribution.
|
| Notes
| -----
| The mean is a coordinate in N-dimensional space, which represents the
| location where samples are most likely to be generated. This is
| analogous to the peak of the bell curve for the one-dimensional or
| univariate normal distribution.
|
| Covariance indicates the level to which two variables vary together.
| From the multivariate normal distribution, we draw N-dimensional
| samples, :math:`X = [x_1, x_2, ... x_N]`. The covariance matrix
| element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`.
| The element :math:`C_{ii}` is the variance of :math:`x_i` (i.e. its
| "spread").
|
| Instead of specifying the full covariance matrix, popular
| approximations include:
|
| - Spherical covariance (`cov` is a multiple of the identity matrix)
| - Diagonal covariance (`cov` has non-negative elements, and only on
| the diagonal)
|
| This geometrical property can be seen in two dimensions by plotting
| generated data-points:
|
| >>> mean = [0, 0]
| >>> cov = [[1, 0], [0, 100]] # diagonal covariance
|
| Diagonal covariance means that points are oriented along x or y-axis:
|
| >>> import matplotlib.pyplot as plt
| >>> rng = np.random.default_rng()
| >>> x, y = rng.multivariate_normal(mean, cov, 5000).T
| >>> plt.plot(x, y, 'x')
| >>> plt.axis('equal')
| >>> plt.show()
|
| Note that the covariance matrix must be positive semidefinite (a.k.a.
| nonnegative-definite). Otherwise, the behavior of this method is
| undefined and backwards compatibility is not guaranteed.
|
| This function internally uses linear algebra routines, and thus results
| may not be identical (even up to precision) across architectures, OSes,
| or even builds. For example, this is likely if ``cov`` has multiple equal
| singular values and ``method`` is ``'svd'`` (default). In this case,
| ``method='cholesky'`` may be more robust.
|
| References
| ----------
| .. [1] Papoulis, A., "Probability, Random Variables, and Stochastic
| Processes," 3rd ed., New York: McGraw-Hill, 1991.
| .. [2] Duda, R. O., Hart, P. E., and Stork, D. G., "Pattern
| Classification," 2nd ed., New York: Wiley, 2001.
|
| Examples
| --------
| >>> mean = (1, 2)
| >>> cov = [[1, 0], [0, 1]]
| >>> rng = np.random.default_rng()
| >>> x = rng.multivariate_normal(mean, cov, (3, 3))
| >>> x.shape
| (3, 3, 2)
|
| We can use a different method other than the default to factorize cov:
|
| >>> y = rng.multivariate_normal(mean, cov, (3, 3), method='cholesky')
| >>> y.shape
| (3, 3, 2)
|
| Here we generate 800 samples from the bivariate normal distribution
| with mean [0, 0] and covariance matrix [[6, -3], [-3, 3.5]]. The
| expected variances of the first and second components of the sample
| are 6 and 3.5, respectively, and the expected correlation
| coefficient is -3/sqrt(6*3.5) ≈ -0.65465.
|
| >>> cov = np.array([[6, -3], [-3, 3.5]])
| >>> pts = rng.multivariate_normal([0, 0], cov, size=800)
|
| Check that the mean, covariance, and correlation coefficient of the
| sample are close to the expected values:
|
| >>> pts.mean(axis=0)
| array([ 0.0326911 , -0.01280782]) # may vary
| >>> np.cov(pts.T)
| array([[ 5.96202397, -2.85602287],
| [-2.85602287, 3.47613949]]) # may vary
| >>> np.corrcoef(pts.T)[0, 1]
| -0.6273591314603949 # may vary
|
| We can visualize this data with a scatter plot. The orientation
| of the point cloud illustrates the negative correlation of the
| components of this sample.
|
| >>> import matplotlib.pyplot as plt
| >>> plt.plot(pts[:, 0], pts[:, 1], '.', alpha=0.5)
| >>> plt.axis('equal')
| >>> plt.grid()
| >>> plt.show()
|
| negative_binomial(self, n, p, size=None)
| negative_binomial(n, p, size=None)
|
| Draw samples from a negative binomial distribution.
|
| Samples are drawn from a negative binomial distribution with specified
| parameters, `n` successes and `p` probability of success where `n`
| is > 0 and `p` is in the interval (0, 1].
|
| Parameters
| ----------
| n : float or array_like of floats
| Parameter of the distribution, > 0.
| p : float or array_like of floats
| Parameter of the distribution. Must satisfy 0 < p <= 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``n`` and ``p`` are both scalars.
| Otherwise, ``np.broadcast(n, p).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized negative binomial distribution,
| where each sample is equal to N, the number of failures that
| occurred before a total of n successes was reached.
|
| Notes
| -----
| The probability mass function of the negative binomial distribution is
|
| .. math:: P(N;n,p) = \frac{\Gamma(N+n)}{N!\Gamma(n)}p^{n}(1-p)^{N},
|
| where :math:`n` is the number of successes, :math:`p` is the
| probability of success, :math:`N+n` is the number of trials, and
| :math:`\Gamma` is the gamma function. When :math:`n` is an integer,
| :math:`\frac{\Gamma(N+n)}{N!\Gamma(n)} = \binom{N+n-1}{N}`, which is
| the more common form of this term in the pmf. The negative
| binomial distribution gives the probability of N failures given n
| successes, with a success on the last trial.
|
| If one throws a die repeatedly until the third time a "1" appears,
| then the probability distribution of the number of non-"1"s that
| appear before the third "1" is a negative binomial distribution.
|
| Because this method internally calls ``Generator.poisson`` with an
| intermediate random value, a ValueError is raised when the choice of
| :math:`n` and :math:`p` would result in the mean + 10 sigma of the sampled
| intermediate distribution exceeding the max acceptable value of the
| ``Generator.poisson`` method. This happens when :math:`p` is too low
| (a lot of failures happen for every success) and :math:`n` is too big (
| a lot of successes are allowed).
| Therefore, the :math:`n` and :math:`p` values must satisfy the constraint:
|
| .. math:: n\frac{1-p}{p}+10n\sqrt{n}\frac{1-p}{p}<2^{63}-1-10\sqrt{2^{63}-1},
|
| Where the left side of the equation is the derived mean + 10 sigma of
| a sample from the gamma distribution internally used as the :math:`lam`
| parameter of a poisson sample, and the right side of the equation is
| the constraint for maximum value of :math:`lam` in ``Generator.poisson``.
|
| References
| ----------
| .. [1] Weisstein, Eric W. "Negative Binomial Distribution." From
| MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/NegativeBinomialDistribution.html
| .. [2] Wikipedia, "Negative binomial distribution",
| https://en.wikipedia.org/wiki/Negative_binomial_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| A real world example. A company drills wild-cat oil
| exploration wells, each with an estimated probability of
| success of 0.1. What is the probability of having one success
| for each successive well, that is what is the probability of a
| single success after drilling 5 wells, after 6 wells, etc.?
|
| >>> rng = np.random.default_rng()
| >>> s = rng.negative_binomial(1, 0.1, 100000)
| >>> for i in range(1, 11): # doctest: +SKIP
| ... probability = sum(s<i) / 100000.
| ... print(i, "wells drilled, probability of one success =", probability)
|
| noncentral_chisquare(self, df, nonc, size=None)
| noncentral_chisquare(df, nonc, size=None)
|
| Draw samples from a noncentral chi-square distribution.
|
| The noncentral :math:`\chi^2` distribution is a generalization of
| the :math:`\chi^2` distribution.
|
| Parameters
| ----------
| df : float or array_like of floats
| Degrees of freedom, must be > 0.
|
| .. versionchanged:: 1.10.0
| Earlier NumPy versions required dfnum > 1.
| nonc : float or array_like of floats
| Non-centrality, must be non-negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``df`` and ``nonc`` are both scalars.
| Otherwise, ``np.broadcast(df, nonc).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized noncentral chi-square distribution.
|
| Notes
| -----
| The probability density function for the noncentral Chi-square
| distribution is
|
| .. math:: P(x;df,nonc) = \sum^{\infty}_{i=0}
| \frac{e^{-nonc/2}(nonc/2)^{i}}{i!}
| P_{Y_{df+2i}}(x),
|
| where :math:`Y_{q}` is the Chi-square with q degrees of freedom.
|
| References
| ----------
| .. [1] Wikipedia, "Noncentral chi-squared distribution"
| https://en.wikipedia.org/wiki/Noncentral_chi-squared_distribution
|
| Examples
| --------
| Draw values from the distribution and plot the histogram
|
| >>> rng = np.random.default_rng()
| >>> import matplotlib.pyplot as plt
| >>> values = plt.hist(rng.noncentral_chisquare(3, 20, 100000),
| ... bins=200, density=True)
| >>> plt.show()
|
| Draw values from a noncentral chisquare with very small noncentrality,
| and compare to a chisquare.
|
| >>> plt.figure()
| >>> values = plt.hist(rng.noncentral_chisquare(3, .0000001, 100000),
| ... bins=np.arange(0., 25, .1), density=True)
| >>> values2 = plt.hist(rng.chisquare(3, 100000),
| ... bins=np.arange(0., 25, .1), density=True)
| >>> plt.plot(values[1][0:-1], values[0]-values2[0], 'ob')
| >>> plt.show()
|
| Demonstrate how large values of non-centrality lead to a more symmetric
| distribution.
|
| >>> plt.figure()
| >>> values = plt.hist(rng.noncentral_chisquare(3, 20, 100000),
| ... bins=200, density=True)
| >>> plt.show()
|
| noncentral_f(self, dfnum, dfden, nonc, size=None)
| noncentral_f(dfnum, dfden, nonc, size=None)
|
| Draw samples from the noncentral F distribution.
|
| Samples are drawn from an F distribution with specified parameters,
| `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of
| freedom in denominator), where both parameters > 1.
| `nonc` is the non-centrality parameter.
|
| Parameters
| ----------
| dfnum : float or array_like of floats
| Numerator degrees of freedom, must be > 0.
|
| .. versionchanged:: 1.14.0
| Earlier NumPy versions required dfnum > 1.
| dfden : float or array_like of floats
| Denominator degrees of freedom, must be > 0.
| nonc : float or array_like of floats
| Non-centrality parameter, the sum of the squares of the numerator
| means, must be >= 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``dfnum``, ``dfden``, and ``nonc``
| are all scalars. Otherwise, ``np.broadcast(dfnum, dfden, nonc).size``
| samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized noncentral Fisher distribution.
|
| Notes
| -----
| When calculating the power of an experiment (power = probability of
| rejecting the null hypothesis when a specific alternative is true) the
| non-central F statistic becomes important. When the null hypothesis is
| true, the F statistic follows a central F distribution. When the null
| hypothesis is not true, then it follows a non-central F statistic.
|
| References
| ----------
| .. [1] Weisstein, Eric W. "Noncentral F-Distribution."
| From MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/NoncentralF-Distribution.html
| .. [2] Wikipedia, "Noncentral F-distribution",
| https://en.wikipedia.org/wiki/Noncentral_F-distribution
|
| Examples
| --------
| In a study, testing for a specific alternative to the null hypothesis
| requires use of the Noncentral F distribution. We need to calculate the
| area in the tail of the distribution that exceeds the value of the F
| distribution for the null hypothesis. We'll plot the two probability
| distributions for comparison.
|
| >>> rng = np.random.default_rng()
| >>> dfnum = 3 # between group deg of freedom
| >>> dfden = 20 # within groups degrees of freedom
| >>> nonc = 3.0
| >>> nc_vals = rng.noncentral_f(dfnum, dfden, nonc, 1000000)
| >>> NF = np.histogram(nc_vals, bins=50, density=True)
| >>> c_vals = rng.f(dfnum, dfden, 1000000)
| >>> F = np.histogram(c_vals, bins=50, density=True)
| >>> import matplotlib.pyplot as plt
| >>> plt.plot(F[1][1:], F[0])
| >>> plt.plot(NF[1][1:], NF[0])
| >>> plt.show()
|
| normal(self, loc=0.0, scale=1.0, size=None)
| normal(loc=0.0, scale=1.0, size=None)
|
| Draw random samples from a normal (Gaussian) distribution.
|
| The probability density function of the normal distribution, first
| derived by De Moivre and 200 years later by both Gauss and Laplace
| independently [2]_, is often called the bell curve because of
| its characteristic shape (see the example below).
|
| The normal distributions occurs often in nature. For example, it
| describes the commonly occurring distribution of samples influenced
| by a large number of tiny, random disturbances, each with its own
| unique distribution [2]_.
|
| Parameters
| ----------
| loc : float or array_like of floats
| Mean ("centre") of the distribution.
| scale : float or array_like of floats
| Standard deviation (spread or "width") of the distribution. Must be
| non-negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``loc`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized normal distribution.
|
| See Also
| --------
| scipy.stats.norm : probability density function, distribution or
| cumulative density function, etc.
|
| Notes
| -----
| The probability density for the Gaussian distribution is
|
| .. math:: p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }}
| e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },
|
| where :math:`\mu` is the mean and :math:`\sigma` the standard
| deviation. The square of the standard deviation, :math:`\sigma^2`,
| is called the variance.
|
| The function has its peak at the mean, and its "spread" increases with
| the standard deviation (the function reaches 0.607 times its maximum at
| :math:`x + \sigma` and :math:`x - \sigma` [2]_). This implies that
| :meth:`normal` is more likely to return samples lying close to the
| mean, rather than those far away.
|
| References
| ----------
| .. [1] Wikipedia, "Normal distribution",
| https://en.wikipedia.org/wiki/Normal_distribution
| .. [2] P. R. Peebles Jr., "Central Limit Theorem" in "Probability,
| Random Variables and Random Signal Principles", 4th ed., 2001,
| pp. 51, 51, 125.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> mu, sigma = 0, 0.1 # mean and standard deviation
| >>> rng = np.random.default_rng()
| >>> s = rng.normal(mu, sigma, 1000)
|
| Verify the mean and the variance:
|
| >>> abs(mu - np.mean(s))
| 0.0 # may vary
|
| >>> abs(sigma - np.std(s, ddof=1))
| 0.0 # may vary
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, _ = plt.hist(s, 30, density=True)
| >>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
| ... np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
| ... linewidth=2, color='r')
| >>> plt.show()
|
| Two-by-four array of samples from the normal distribution with
| mean 3 and standard deviation 2.5:
|
| >>> rng = np.random.default_rng()
| >>> rng.normal(3, 2.5, size=(2, 4))
| array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random
| [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random
|
| pareto(self, a, size=None)
| pareto(a, size=None)
|
| Draw samples from a Pareto II (AKA Lomax) distribution with
| specified shape.
|
| Parameters
| ----------
| a : float or array_like of floats
| Shape of the distribution. Must be positive.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``a`` is a scalar. Otherwise,
| ``np.array(a).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the Pareto II distribution.
|
| See Also
| --------
| scipy.stats.pareto : Pareto I distribution
| scipy.stats.lomax : Lomax (Pareto II) distribution
| scipy.stats.genpareto : Generalized Pareto distribution
|
| Notes
| -----
| The probability density for the Pareto II distribution is
|
| .. math:: p(x) = \frac{a}{{x+1}^{a+1}} , x \ge 0
|
| where :math:`a > 0` is the shape.
|
| The Pareto II distribution is a shifted and scaled version of the
| Pareto I distribution, which can be found in `scipy.stats.pareto`.
|
| References
| ----------
| .. [1] Francis Hunt and Paul Johnson, On the Pareto Distribution of
| Sourceforge projects.
| .. [2] Pareto, V. (1896). Course of Political Economy. Lausanne.
| .. [3] Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme
| Values, Birkhauser Verlag, Basel, pp 23-30.
| .. [4] Wikipedia, "Pareto distribution",
| https://en.wikipedia.org/wiki/Pareto_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> a = 3.
| >>> rng = np.random.default_rng()
| >>> s = rng.pareto(a, 10000)
|
| Display the histogram of the samples, along with the probability
| density function:
|
| >>> import matplotlib.pyplot as plt
| >>> x = np.linspace(0, 3, 50)
| >>> pdf = a / (x+1)**(a+1)
| >>> plt.hist(s, bins=x, density=True, label='histogram')
| >>> plt.plot(x, pdf, linewidth=2, color='r', label='pdf')
| >>> plt.xlim(x.min(), x.max())
| >>> plt.legend()
| >>> plt.show()
|
| permutation(self, x, axis=0)
| permutation(x, axis=0)
|
| Randomly permute a sequence, or return a permuted range.
|
| Parameters
| ----------
| x : int or array_like
| If `x` is an integer, randomly permute ``np.arange(x)``.
| If `x` is an array, make a copy and shuffle the elements
| randomly.
| axis : int, optional
| The axis which `x` is shuffled along. Default is 0.
|
| Returns
| -------
| out : ndarray
| Permuted sequence or array range.
|
| Examples
| --------
| >>> rng = np.random.default_rng()
| >>> rng.permutation(10)
| array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6]) # random
|
| >>> rng.permutation([1, 4, 9, 12, 15])
| array([15, 1, 9, 4, 12]) # random
|
| >>> arr = np.arange(9).reshape((3, 3))
| >>> rng.permutation(arr)
| array([[6, 7, 8], # random
| [0, 1, 2],
| [3, 4, 5]])
|
| >>> rng.permutation("abc")
| Traceback (most recent call last):
| ...
| numpy.exceptions.AxisError: axis 0 is out of bounds for array of dimension 0
|
| >>> arr = np.arange(9).reshape((3, 3))
| >>> rng.permutation(arr, axis=1)
| array([[0, 2, 1], # random
| [3, 5, 4],
| [6, 8, 7]])
|
| permuted(self, x, *, axis=None, out=None)
| permuted(x, axis=None, out=None)
|
| Randomly permute `x` along axis `axis`.
|
| Unlike `shuffle`, each slice along the given axis is shuffled
| independently of the others.
|
| Parameters
| ----------
| x : array_like, at least one-dimensional
| Array to be shuffled.
| axis : int, optional
| Slices of `x` in this axis are shuffled. Each slice
| is shuffled independently of the others. If `axis` is
| None, the flattened array is shuffled.
| out : ndarray, optional
| If given, this is the destination of the shuffled array.
| If `out` is None, a shuffled copy of the array is returned.
|
| Returns
| -------
| ndarray
| If `out` is None, a shuffled copy of `x` is returned.
| Otherwise, the shuffled array is stored in `out`,
| and `out` is returned
|
| See Also
| --------
| shuffle
| permutation
|
| Notes
| -----
| An important distinction between methods ``shuffle`` and ``permuted`` is
| how they both treat the ``axis`` parameter which can be found at
| :ref:`generator-handling-axis-parameter`.
|
| Examples
| --------
| Create a `numpy.random.Generator` instance:
|
| >>> rng = np.random.default_rng()
|
| Create a test array:
|
| >>> x = np.arange(24).reshape(3, 8)
| >>> x
| array([[ 0, 1, 2, 3, 4, 5, 6, 7],
| [ 8, 9, 10, 11, 12, 13, 14, 15],
| [16, 17, 18, 19, 20, 21, 22, 23]])
|
| Shuffle the rows of `x`:
|
| >>> y = rng.permuted(x, axis=1)
| >>> y
| array([[ 4, 3, 6, 7, 1, 2, 5, 0], # random
| [15, 10, 14, 9, 12, 11, 8, 13],
| [17, 16, 20, 21, 18, 22, 23, 19]])
|
| `x` has not been modified:
|
| >>> x
| array([[ 0, 1, 2, 3, 4, 5, 6, 7],
| [ 8, 9, 10, 11, 12, 13, 14, 15],
| [16, 17, 18, 19, 20, 21, 22, 23]])
|
| To shuffle the rows of `x` in-place, pass `x` as the `out`
| parameter:
|
| >>> y = rng.permuted(x, axis=1, out=x)
| >>> x
| array([[ 3, 0, 4, 7, 1, 6, 2, 5], # random
| [ 8, 14, 13, 9, 12, 11, 15, 10],
| [17, 18, 16, 22, 19, 23, 20, 21]])
|
| Note that when the ``out`` parameter is given, the return
| value is ``out``:
|
| >>> y is x
| True
|
| poisson(self, lam=1.0, size=None)
| poisson(lam=1.0, size=None)
|
| Draw samples from a Poisson distribution.
|
| The Poisson distribution is the limit of the binomial distribution
| for large N.
|
| Parameters
| ----------
| lam : float or array_like of floats
| Expected number of events occurring in a fixed-time interval,
| must be >= 0. A sequence must be broadcastable over the requested
| size.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``lam`` is a scalar. Otherwise,
| ``np.array(lam).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Poisson distribution.
|
| Notes
| -----
| The Poisson distribution
|
| .. math:: f(k; \lambda)=\frac{\lambda^k e^{-\lambda}}{k!}
|
| For events with an expected separation :math:`\lambda` the Poisson
| distribution :math:`f(k; \lambda)` describes the probability of
| :math:`k` events occurring within the observed
| interval :math:`\lambda`.
|
| Because the output is limited to the range of the C int64 type, a
| ValueError is raised when `lam` is within 10 sigma of the maximum
| representable value.
|
| References
| ----------
| .. [1] Weisstein, Eric W. "Poisson Distribution."
| From MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/PoissonDistribution.html
| .. [2] Wikipedia, "Poisson distribution",
| https://en.wikipedia.org/wiki/Poisson_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> rng = np.random.default_rng()
| >>> lam, size = 5, 10000
| >>> s = rng.poisson(lam=lam, size=size)
|
| Verify the mean and variance, which should be approximately ``lam``:
|
| >>> s.mean(), s.var()
| (4.9917 5.1088311) # may vary
|
| Display the histogram and probability mass function:
|
| >>> import matplotlib.pyplot as plt
| >>> from scipy import stats
| >>> x = np.arange(0, 21)
| >>> pmf = stats.poisson.pmf(x, mu=lam)
| >>> plt.hist(s, bins=x, density=True, width=0.5)
| >>> plt.stem(x, pmf, 'C1-')
| >>> plt.show()
|
| Draw each 100 values for lambda 100 and 500:
|
| >>> s = rng.poisson(lam=(100., 500.), size=(100, 2))
|
| power(self, a, size=None)
| power(a, size=None)
|
| Draws samples in [0, 1] from a power distribution with positive
| exponent a - 1.
|
| Also known as the power function distribution.
|
| Parameters
| ----------
| a : float or array_like of floats
| Parameter of the distribution. Must be non-negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``a`` is a scalar. Otherwise,
| ``np.array(a).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized power distribution.
|
| Raises
| ------
| ValueError
| If a <= 0.
|
| Notes
| -----
| The probability density function is
|
| .. math:: P(x; a) = ax^{a-1}, 0 \le x \le 1, a>0.
|
| The power function distribution is just the inverse of the Pareto
| distribution. It may also be seen as a special case of the Beta
| distribution.
|
| It is used, for example, in modeling the over-reporting of insurance
| claims.
|
| References
| ----------
| .. [1] Christian Kleiber, Samuel Kotz, "Statistical size distributions
| in economics and actuarial sciences", Wiley, 2003.
| .. [2] Heckert, N. A. and Filliben, James J. "NIST Handbook 148:
| Dataplot Reference Manual, Volume 2: Let Subcommands and Library
| Functions", National Institute of Standards and Technology
| Handbook Series, June 2003.
| https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/powpdf.pdf
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> rng = np.random.default_rng()
| >>> a = 5. # shape
| >>> samples = 1000
| >>> s = rng.power(a, samples)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, _ = plt.hist(s, bins=30)
| >>> x = np.linspace(0, 1, 100)
| >>> y = a*x**(a-1.)
| >>> normed_y = samples*np.diff(bins)[0]*y
| >>> plt.plot(x, normed_y)
| >>> plt.show()
|
| Compare the power function distribution to the inverse of the Pareto.
|
| >>> from scipy import stats # doctest: +SKIP
| >>> rvs = rng.power(5, 1000000)
| >>> rvsp = rng.pareto(5, 1000000)
| >>> xx = np.linspace(0,1,100)
| >>> powpdf = stats.powerlaw.pdf(xx,5) # doctest: +SKIP
|
| >>> plt.figure()
| >>> plt.hist(rvs, bins=50, density=True)
| >>> plt.plot(xx,powpdf,'r-') # doctest: +SKIP
| >>> plt.title('power(5)')
|
| >>> plt.figure()
| >>> plt.hist(1./(1.+rvsp), bins=50, density=True)
| >>> plt.plot(xx,powpdf,'r-') # doctest: +SKIP
| >>> plt.title('inverse of 1 + Generator.pareto(5)')
|
| >>> plt.figure()
| >>> plt.hist(1./(1.+rvsp), bins=50, density=True)
| >>> plt.plot(xx,powpdf,'r-') # doctest: +SKIP
| >>> plt.title('inverse of stats.pareto(5)')
|
| random(self, size=None, dtype=<class 'numpy.float64'>, out=None)
| random(size=None, dtype=np.float64, out=None)
|
| Return random floats in the half-open interval [0.0, 1.0).
|
| Results are from the "continuous uniform" distribution over the
| stated interval. To sample :math:`Unif[a, b), b > a` use `uniform`
| or multiply the output of `random` by ``(b - a)`` and add ``a``::
|
| (b - a) * random() + a
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| dtype : dtype, optional
| Desired dtype of the result, only `float64` and `float32` are supported.
| Byteorder must be native. The default value is np.float64.
| out : ndarray, optional
| Alternative output array in which to place the result. If size is not None,
| it must have the same shape as the provided size and must match the type of
| the output values.
|
| Returns
| -------
| out : float or ndarray of floats
| Array of random floats of shape `size` (unless ``size=None``, in which
| case a single float is returned).
|
| See Also
| --------
| uniform : Draw samples from the parameterized uniform distribution.
|
| Examples
| --------
| >>> rng = np.random.default_rng()
| >>> rng.random()
| 0.47108547995356098 # random
| >>> type(rng.random())
| <class 'float'>
| >>> rng.random((5,))
| array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428]) # random
|
| Three-by-two array of random numbers from [-5, 0):
|
| >>> 5 * rng.random((3, 2)) - 5
| array([[-3.99149989, -0.52338984], # random
| [-2.99091858, -0.79479508],
| [-1.23204345, -1.75224494]])
|
| rayleigh(self, scale=1.0, size=None)
| rayleigh(scale=1.0, size=None)
|
| Draw samples from a Rayleigh distribution.
|
| The :math:`\chi` and Weibull distributions are generalizations of the
| Rayleigh.
|
| Parameters
| ----------
| scale : float or array_like of floats, optional
| Scale, also equals the mode. Must be non-negative. Default is 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``scale`` is a scalar. Otherwise,
| ``np.array(scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Rayleigh distribution.
|
| Notes
| -----
| The probability density function for the Rayleigh distribution is
|
| .. math:: P(x;scale) = \frac{x}{scale^2}e^{\frac{-x^2}{2 \cdotp scale^2}}
|
| The Rayleigh distribution would arise, for example, if the East
| and North components of the wind velocity had identical zero-mean
| Gaussian distributions. Then the wind speed would have a Rayleigh
| distribution.
|
| References
| ----------
| .. [1] Brighton Webs Ltd., "Rayleigh Distribution,"
| https://web.archive.org/web/20090514091424/http://brighton-webs.co.uk:80/distributions/rayleigh.asp
| .. [2] Wikipedia, "Rayleigh distribution"
| https://en.wikipedia.org/wiki/Rayleigh_distribution
|
| Examples
| --------
| Draw values from the distribution and plot the histogram
|
| >>> from matplotlib.pyplot import hist
| >>> rng = np.random.default_rng()
| >>> values = hist(rng.rayleigh(3, 100000), bins=200, density=True)
|
| Wave heights tend to follow a Rayleigh distribution. If the mean wave
| height is 1 meter, what fraction of waves are likely to be larger than 3
| meters?
|
| >>> meanvalue = 1
| >>> modevalue = np.sqrt(2 / np.pi) * meanvalue
| >>> s = rng.rayleigh(modevalue, 1000000)
|
| The percentage of waves larger than 3 meters is:
|
| >>> 100.*sum(s>3)/1000000.
| 0.087300000000000003 # random
|
| shuffle(self, x, axis=0)
| shuffle(x, axis=0)
|
| Modify an array or sequence in-place by shuffling its contents.
|
| The order of sub-arrays is changed but their contents remains the same.
|
| Parameters
| ----------
| x : ndarray or MutableSequence
| The array, list or mutable sequence to be shuffled.
| axis : int, optional
| The axis which `x` is shuffled along. Default is 0.
| It is only supported on `ndarray` objects.
|
| Returns
| -------
| None
|
| See Also
| --------
| permuted
| permutation
|
| Notes
| -----
| An important distinction between methods ``shuffle`` and ``permuted`` is
| how they both treat the ``axis`` parameter which can be found at
| :ref:`generator-handling-axis-parameter`.
|
| Examples
| --------
| >>> rng = np.random.default_rng()
| >>> arr = np.arange(10)
| >>> arr
| array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
| >>> rng.shuffle(arr)
| >>> arr
| array([2, 0, 7, 5, 1, 4, 8, 9, 3, 6]) # random
|
| >>> arr = np.arange(9).reshape((3, 3))
| >>> arr
| array([[0, 1, 2],
| [3, 4, 5],
| [6, 7, 8]])
| >>> rng.shuffle(arr)
| >>> arr
| array([[3, 4, 5], # random
| [6, 7, 8],
| [0, 1, 2]])
|
| >>> arr = np.arange(9).reshape((3, 3))
| >>> arr
| array([[0, 1, 2],
| [3, 4, 5],
| [6, 7, 8]])
| >>> rng.shuffle(arr, axis=1)
| >>> arr
| array([[2, 0, 1], # random
| [5, 3, 4],
| [8, 6, 7]])
|
| spawn(self, n_children)
| spawn(n_children)
|
| Create new independent child generators.
|
| See :ref:`seedsequence-spawn` for additional notes on spawning
| children.
|
| .. versionadded:: 1.25.0
|
| Parameters
| ----------
| n_children : int
|
| Returns
| -------
| child_generators : list of Generators
|
| Raises
| ------
| TypeError
| When the underlying SeedSequence does not implement spawning.
|
| See Also
| --------
| random.BitGenerator.spawn, random.SeedSequence.spawn :
| Equivalent method on the bit generator and seed sequence.
| bit_generator :
| The bit generator instance used by the generator.
|
| Examples
| --------
| Starting from a seeded default generator:
|
| >>> # High quality entropy created with: f"0x{secrets.randbits(128):x}"
| >>> entropy = 0x3034c61a9ae04ff8cb62ab8ec2c4b501
| >>> rng = np.random.default_rng(entropy)
|
| Create two new generators for example for parallel execution:
|
| >>> child_rng1, child_rng2 = rng.spawn(2)
|
| Drawn numbers from each are independent but derived from the initial
| seeding entropy:
|
| >>> rng.uniform(), child_rng1.uniform(), child_rng2.uniform()
| (0.19029263503854454, 0.9475673279178444, 0.4702687338396767)
|
| It is safe to spawn additional children from the original ``rng`` or
| the children:
|
| >>> more_child_rngs = rng.spawn(20)
| >>> nested_spawn = child_rng1.spawn(20)
|
| standard_cauchy(self, size=None)
| standard_cauchy(size=None)
|
| Draw samples from a standard Cauchy distribution with mode = 0.
|
| Also known as the Lorentz distribution.
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
|
| Returns
| -------
| samples : ndarray or scalar
| The drawn samples.
|
| Notes
| -----
| The probability density function for the full Cauchy distribution is
|
| .. math:: P(x; x_0, \gamma) = \frac{1}{\pi \gamma \bigl[ 1+
| (\frac{x-x_0}{\gamma})^2 \bigr] }
|
| and the Standard Cauchy distribution just sets :math:`x_0=0` and
| :math:`\gamma=1`
|
| The Cauchy distribution arises in the solution to the driven harmonic
| oscillator problem, and also describes spectral line broadening. It
| also describes the distribution of values at which a line tilted at
| a random angle will cut the x axis.
|
| When studying hypothesis tests that assume normality, seeing how the
| tests perform on data from a Cauchy distribution is a good indicator of
| their sensitivity to a heavy-tailed distribution, since the Cauchy looks
| very much like a Gaussian distribution, but with heavier tails.
|
| References
| ----------
| .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "Cauchy
| Distribution",
| https://www.itl.nist.gov/div898/handbook/eda/section3/eda3663.htm
| .. [2] Weisstein, Eric W. "Cauchy Distribution." From MathWorld--A
| Wolfram Web Resource.
| https://mathworld.wolfram.com/CauchyDistribution.html
| .. [3] Wikipedia, "Cauchy distribution"
| https://en.wikipedia.org/wiki/Cauchy_distribution
|
| Examples
| --------
| Draw samples and plot the distribution:
|
| >>> import matplotlib.pyplot as plt
| >>> rng = np.random.default_rng()
| >>> s = rng.standard_cauchy(1000000)
| >>> s = s[(s>-25) & (s<25)] # truncate distribution so it plots well
| >>> plt.hist(s, bins=100)
| >>> plt.show()
|
| standard_exponential(self, size=None, dtype=<class 'numpy.float64'>, method='zig', out=None)
| standard_exponential(size=None, dtype=np.float64, method='zig', out=None)
|
| Draw samples from the standard exponential distribution.
|
| `standard_exponential` is identical to the exponential distribution
| with a scale parameter of 1.
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| dtype : dtype, optional
| Desired dtype of the result, only `float64` and `float32` are supported.
| Byteorder must be native. The default value is np.float64.
| method : str, optional
| Either 'inv' or 'zig'. 'inv' uses the default inverse CDF method.
| 'zig' uses the much faster Ziggurat method of Marsaglia and Tsang.
| out : ndarray, optional
| Alternative output array in which to place the result. If size is not None,
| it must have the same shape as the provided size and must match the type of
| the output values.
|
| Returns
| -------
| out : float or ndarray
| Drawn samples.
|
| Examples
| --------
| Output a 3x8000 array:
|
| >>> rng = np.random.default_rng()
| >>> n = rng.standard_exponential((3, 8000))
|
| standard_gamma(self, shape, size=None, dtype=<class 'numpy.float64'>, out=None)
| standard_gamma(shape, size=None, dtype=np.float64, out=None)
|
| Draw samples from a standard Gamma distribution.
|
| Samples are drawn from a Gamma distribution with specified parameters,
| shape (sometimes designated "k") and scale=1.
|
| Parameters
| ----------
| shape : float or array_like of floats
| Parameter, must be non-negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``shape`` is a scalar. Otherwise,
| ``np.array(shape).size`` samples are drawn.
| dtype : dtype, optional
| Desired dtype of the result, only `float64` and `float32` are supported.
| Byteorder must be native. The default value is np.float64.
| out : ndarray, optional
| Alternative output array in which to place the result. If size is
| not None, it must have the same shape as the provided size and
| must match the type of the output values.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized standard gamma distribution.
|
| See Also
| --------
| scipy.stats.gamma : probability density function, distribution or
| cumulative density function, etc.
|
| Notes
| -----
| The probability density for the Gamma distribution is
|
| .. math:: p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},
|
| where :math:`k` is the shape and :math:`\theta` the scale,
| and :math:`\Gamma` is the Gamma function.
|
| The Gamma distribution is often used to model the times to failure of
| electronic components, and arises naturally in processes for which the
| waiting times between Poisson distributed events are relevant.
|
| References
| ----------
| .. [1] Weisstein, Eric W. "Gamma Distribution." From MathWorld--A
| Wolfram Web Resource.
| https://mathworld.wolfram.com/GammaDistribution.html
| .. [2] Wikipedia, "Gamma distribution",
| https://en.wikipedia.org/wiki/Gamma_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> shape, scale = 2., 1. # mean and width
| >>> rng = np.random.default_rng()
| >>> s = rng.standard_gamma(shape, 1000000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> import scipy.special as sps # doctest: +SKIP
| >>> count, bins, _ = plt.hist(s, 50, density=True)
| >>> y = bins**(shape-1) * ((np.exp(-bins/scale))/ # doctest: +SKIP
| ... (sps.gamma(shape) * scale**shape))
| >>> plt.plot(bins, y, linewidth=2, color='r') # doctest: +SKIP
| >>> plt.show()
|
| standard_normal(self, size=None, dtype=<class 'numpy.float64'>, out=None)
| standard_normal(size=None, dtype=np.float64, out=None)
|
| Draw samples from a standard Normal distribution (mean=0, stdev=1).
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| dtype : dtype, optional
| Desired dtype of the result, only `float64` and `float32` are supported.
| Byteorder must be native. The default value is np.float64.
| out : ndarray, optional
| Alternative output array in which to place the result. If size is not None,
| it must have the same shape as the provided size and must match the type of
| the output values.
|
| Returns
| -------
| out : float or ndarray
| A floating-point array of shape ``size`` of drawn samples, or a
| single sample if ``size`` was not specified.
|
| See Also
| --------
| normal :
| Equivalent function with additional ``loc`` and ``scale`` arguments
| for setting the mean and standard deviation.
|
| Notes
| -----
| For random samples from the normal distribution with mean ``mu`` and
| standard deviation ``sigma``, use one of::
|
| mu + sigma * rng.standard_normal(size=...)
| rng.normal(mu, sigma, size=...)
|
| Examples
| --------
| >>> rng = np.random.default_rng()
| >>> rng.standard_normal()
| 2.1923875335537315 # random
|
| >>> s = rng.standard_normal(8000)
| >>> s
| array([ 0.6888893 , 0.78096262, -0.89086505, ..., 0.49876311, # random
| -0.38672696, -0.4685006 ]) # random
| >>> s.shape
| (8000,)
| >>> s = rng.standard_normal(size=(3, 4, 2))
| >>> s.shape
| (3, 4, 2)
|
| Two-by-four array of samples from the normal distribution with
| mean 3 and standard deviation 2.5:
|
| >>> 3 + 2.5 * rng.standard_normal(size=(2, 4))
| array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random
| [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random
|
| standard_t(self, df, size=None)
| standard_t(df, size=None)
|
| Draw samples from a standard Student's t distribution with `df` degrees
| of freedom.
|
| A special case of the hyperbolic distribution. As `df` gets
| large, the result resembles that of the standard normal
| distribution (`standard_normal`).
|
| Parameters
| ----------
| df : float or array_like of floats
| Degrees of freedom, must be > 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``df`` is a scalar. Otherwise,
| ``np.array(df).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized standard Student's t distribution.
|
| Notes
| -----
| The probability density function for the t distribution is
|
| .. math:: P(x, df) = \frac{\Gamma(\frac{df+1}{2})}{\sqrt{\pi df}
| \Gamma(\frac{df}{2})}\Bigl( 1+\frac{x^2}{df} \Bigr)^{-(df+1)/2}
|
| The t test is based on an assumption that the data come from a
| Normal distribution. The t test provides a way to test whether
| the sample mean (that is the mean calculated from the data) is
| a good estimate of the true mean.
|
| The derivation of the t-distribution was first published in
| 1908 by William Gosset while working for the Guinness Brewery
| in Dublin. Due to proprietary issues, he had to publish under
| a pseudonym, and so he used the name Student.
|
| References
| ----------
| .. [1] Dalgaard, Peter, "Introductory Statistics With R",
| Springer, 2002.
| .. [2] Wikipedia, "Student's t-distribution"
| https://en.wikipedia.org/wiki/Student's_t-distribution
|
| Examples
| --------
| From Dalgaard page 83 [1]_, suppose the daily energy intake for 11
| women in kilojoules (kJ) is:
|
| >>> intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515, \
| ... 7515, 8230, 8770])
|
| Does their energy intake deviate systematically from the recommended
| value of 7725 kJ? Our null hypothesis will be the absence of deviation,
| and the alternate hypothesis will be the presence of an effect that could be
| either positive or negative, hence making our test 2-tailed.
|
| Because we are estimating the mean and we have N=11 values in our sample,
| we have N-1=10 degrees of freedom. We set our significance level to 95% and
| compute the t statistic using the empirical mean and empirical standard
| deviation of our intake. We use a ddof of 1 to base the computation of our
| empirical standard deviation on an unbiased estimate of the variance (note:
| the final estimate is not unbiased due to the concave nature of the square
| root).
|
| >>> np.mean(intake)
| 6753.636363636364
| >>> intake.std(ddof=1)
| 1142.1232221373727
| >>> t = (np.mean(intake)-7725)/(intake.std(ddof=1)/np.sqrt(len(intake)))
| >>> t
| -2.8207540608310198
|
| We draw 1000000 samples from Student's t distribution with the adequate
| degrees of freedom.
|
| >>> import matplotlib.pyplot as plt
| >>> rng = np.random.default_rng()
| >>> s = rng.standard_t(10, size=1000000)
| >>> h = plt.hist(s, bins=100, density=True)
|
| Does our t statistic land in one of the two critical regions found at
| both tails of the distribution?
|
| >>> np.sum(np.abs(t) < np.abs(s)) / float(len(s))
| 0.018318 #random < 0.05, statistic is in critical region
|
| The probability value for this 2-tailed test is about 1.83%, which is
| lower than the 5% pre-determined significance threshold.
|
| Therefore, the probability of observing values as extreme as our intake
| conditionally on the null hypothesis being true is too low, and we reject
| the null hypothesis of no deviation.
|
| triangular(self, left, mode, right, size=None)
| triangular(left, mode, right, size=None)
|
| Draw samples from the triangular distribution over the
| interval ``[left, right]``.
|
| The triangular distribution is a continuous probability
| distribution with lower limit left, peak at mode, and upper
| limit right. Unlike the other distributions, these parameters
| directly define the shape of the pdf.
|
| Parameters
| ----------
| left : float or array_like of floats
| Lower limit.
| mode : float or array_like of floats
| The value where the peak of the distribution occurs.
| The value must fulfill the condition ``left <= mode <= right``.
| right : float or array_like of floats
| Upper limit, must be larger than `left`.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``left``, ``mode``, and ``right``
| are all scalars. Otherwise, ``np.broadcast(left, mode, right).size``
| samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized triangular distribution.
|
| Notes
| -----
| The probability density function for the triangular distribution is
|
| .. math:: P(x;l, m, r) = \begin{cases}
| \frac{2(x-l)}{(r-l)(m-l)}& \text{for $l \leq x \leq m$},\\
| \frac{2(r-x)}{(r-l)(r-m)}& \text{for $m \leq x \leq r$},\\
| 0& \text{otherwise}.
| \end{cases}
|
| The triangular distribution is often used in ill-defined
| problems where the underlying distribution is not known, but
| some knowledge of the limits and mode exists. Often it is used
| in simulations.
|
| References
| ----------
| .. [1] Wikipedia, "Triangular distribution"
| https://en.wikipedia.org/wiki/Triangular_distribution
|
| Examples
| --------
| Draw values from the distribution and plot the histogram:
|
| >>> import matplotlib.pyplot as plt
| >>> rng = np.random.default_rng()
| >>> h = plt.hist(rng.triangular(-3, 0, 8, 100000), bins=200,
| ... density=True)
| >>> plt.show()
|
| uniform(self, low=0.0, high=1.0, size=None)
| uniform(low=0.0, high=1.0, size=None)
|
| Draw samples from a uniform distribution.
|
| Samples are uniformly distributed over the half-open interval
| ``[low, high)`` (includes low, but excludes high). In other words,
| any value within the given interval is equally likely to be drawn
| by `uniform`.
|
| Parameters
| ----------
| low : float or array_like of floats, optional
| Lower boundary of the output interval. All values generated will be
| greater than or equal to low. The default value is 0.
| high : float or array_like of floats
| Upper boundary of the output interval. All values generated will be
| less than high. The high limit may be included in the returned array of
| floats due to floating-point rounding in the equation
| ``low + (high-low) * random_sample()``. high - low must be
| non-negative. The default value is 1.0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``low`` and ``high`` are both scalars.
| Otherwise, ``np.broadcast(low, high).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized uniform distribution.
|
| See Also
| --------
| integers : Discrete uniform distribution, yielding integers.
| random : Floats uniformly distributed over ``[0, 1)``.
|
| Notes
| -----
| The probability density function of the uniform distribution is
|
| .. math:: p(x) = \frac{1}{b - a}
|
| anywhere within the interval ``[a, b)``, and zero elsewhere.
|
| When ``high`` == ``low``, values of ``low`` will be returned.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> rng = np.random.default_rng()
| >>> s = rng.uniform(-1,0,1000)
|
| All values are within the given interval:
|
| >>> np.all(s >= -1)
| True
| >>> np.all(s < 0)
| True
|
| Display the histogram of the samples, along with the
| probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, _ = plt.hist(s, 15, density=True)
| >>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
| >>> plt.show()
|
| vonmises(self, mu, kappa, size=None)
| vonmises(mu, kappa, size=None)
|
| Draw samples from a von Mises distribution.
|
| Samples are drawn from a von Mises distribution with specified mode
| (mu) and dispersion (kappa), on the interval [-pi, pi].
|
| The von Mises distribution (also known as the circular normal
| distribution) is a continuous probability distribution on the unit
| circle. It may be thought of as the circular analogue of the normal
| distribution.
|
| Parameters
| ----------
| mu : float or array_like of floats
| Mode ("center") of the distribution.
| kappa : float or array_like of floats
| Dispersion of the distribution, has to be >=0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``mu`` and ``kappa`` are both scalars.
| Otherwise, ``np.broadcast(mu, kappa).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized von Mises distribution.
|
| See Also
| --------
| scipy.stats.vonmises : probability density function, distribution, or
| cumulative density function, etc.
|
| Notes
| -----
| The probability density for the von Mises distribution is
|
| .. math:: p(x) = \frac{e^{\kappa cos(x-\mu)}}{2\pi I_0(\kappa)},
|
| where :math:`\mu` is the mode and :math:`\kappa` the dispersion,
| and :math:`I_0(\kappa)` is the modified Bessel function of order 0.
|
| The von Mises is named for Richard Edler von Mises, who was born in
| Austria-Hungary, in what is now the Ukraine. He fled to the United
| States in 1939 and became a professor at Harvard. He worked in
| probability theory, aerodynamics, fluid mechanics, and philosophy of
| science.
|
| References
| ----------
| .. [1] Abramowitz, M. and Stegun, I. A. (Eds.). "Handbook of
| Mathematical Functions with Formulas, Graphs, and Mathematical
| Tables, 9th printing," New York: Dover, 1972.
| .. [2] von Mises, R., "Mathematical Theory of Probability
| and Statistics", New York: Academic Press, 1964.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> mu, kappa = 0.0, 4.0 # mean and dispersion
| >>> rng = np.random.default_rng()
| >>> s = rng.vonmises(mu, kappa, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> from scipy.special import i0 # doctest: +SKIP
| >>> plt.hist(s, 50, density=True)
| >>> x = np.linspace(-np.pi, np.pi, num=51)
| >>> y = np.exp(kappa*np.cos(x-mu))/(2*np.pi*i0(kappa)) # doctest: +SKIP
| >>> plt.plot(x, y, linewidth=2, color='r') # doctest: +SKIP
| >>> plt.show()
|
| wald(self, mean, scale, size=None)
| wald(mean, scale, size=None)
|
| Draw samples from a Wald, or inverse Gaussian, distribution.
|
| As the scale approaches infinity, the distribution becomes more like a
| Gaussian. Some references claim that the Wald is an inverse Gaussian
| with mean equal to 1, but this is by no means universal.
|
| The inverse Gaussian distribution was first studied in relationship to
| Brownian motion. In 1956 M.C.K. Tweedie used the name inverse Gaussian
| because there is an inverse relationship between the time to cover a
| unit distance and distance covered in unit time.
|
| Parameters
| ----------
| mean : float or array_like of floats
| Distribution mean, must be > 0.
| scale : float or array_like of floats
| Scale parameter, must be > 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``mean`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(mean, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Wald distribution.
|
| Notes
| -----
| The probability density function for the Wald distribution is
|
| .. math:: P(x;mean,scale) = \sqrt{\frac{scale}{2\pi x^3}}e^
| \frac{-scale(x-mean)^2}{2\cdotp mean^2x}
|
| As noted above the inverse Gaussian distribution first arise
| from attempts to model Brownian motion. It is also a
| competitor to the Weibull for use in reliability modeling and
| modeling stock returns and interest rate processes.
|
| References
| ----------
| .. [1] Brighton Webs Ltd., Wald Distribution,
| https://web.archive.org/web/20090423014010/http://www.brighton-webs.co.uk:80/distributions/wald.asp
| .. [2] Chhikara, Raj S., and Folks, J. Leroy, "The Inverse Gaussian
| Distribution: Theory : Methodology, and Applications", CRC Press,
| 1988.
| .. [3] Wikipedia, "Inverse Gaussian distribution"
| https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution
|
| Examples
| --------
| Draw values from the distribution and plot the histogram:
|
| >>> import matplotlib.pyplot as plt
| >>> rng = np.random.default_rng()
| >>> h = plt.hist(rng.wald(3, 2, 100000), bins=200, density=True)
| >>> plt.show()
|
| weibull(self, a, size=None)
| weibull(a, size=None)
|
| Draw samples from a Weibull distribution.
|
| Draw samples from a 1-parameter Weibull distribution with the given
| shape parameter `a`.
|
| .. math:: X = (-ln(U))^{1/a}
|
| Here, U is drawn from the uniform distribution over (0,1].
|
| The more common 2-parameter Weibull, including a scale parameter
| :math:`\lambda` is just :math:`X = \lambda(-ln(U))^{1/a}`.
|
| Parameters
| ----------
| a : float or array_like of floats
| Shape parameter of the distribution. Must be nonnegative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``a`` is a scalar. Otherwise,
| ``np.array(a).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Weibull distribution.
|
| See Also
| --------
| scipy.stats.weibull_max
| scipy.stats.weibull_min
| scipy.stats.genextreme
| gumbel
|
| Notes
| -----
| The Weibull (or Type III asymptotic extreme value distribution
| for smallest values, SEV Type III, or Rosin-Rammler
| distribution) is one of a class of Generalized Extreme Value
| (GEV) distributions used in modeling extreme value problems.
| This class includes the Gumbel and Frechet distributions.
|
| The probability density for the Weibull distribution is
|
| .. math:: p(x) = \frac{a}
| {\lambda}(\frac{x}{\lambda})^{a-1}e^{-(x/\lambda)^a},
|
| where :math:`a` is the shape and :math:`\lambda` the scale.
|
| The function has its peak (the mode) at
| :math:`\lambda(\frac{a-1}{a})^{1/a}`.
|
| When ``a = 1``, the Weibull distribution reduces to the exponential
| distribution.
|
| References
| ----------
| .. [1] Waloddi Weibull, Royal Technical University, Stockholm,
| 1939 "A Statistical Theory Of The Strength Of Materials",
| Ingeniorsvetenskapsakademiens Handlingar Nr 151, 1939,
| Generalstabens Litografiska Anstalts Forlag, Stockholm.
| .. [2] Waloddi Weibull, "A Statistical Distribution Function of
| Wide Applicability", Journal Of Applied Mechanics ASME Paper
| 1951.
| .. [3] Wikipedia, "Weibull distribution",
| https://en.wikipedia.org/wiki/Weibull_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> rng = np.random.default_rng()
| >>> a = 5. # shape
| >>> s = rng.weibull(a, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> def weibull(x, n, a):
| ... return (a / n) * (x / n)**(a - 1) * np.exp(-(x / n)**a)
| >>> count, bins, _ = plt.hist(rng.weibull(5., 1000))
| >>> x = np.linspace(0, 2, 1000)
| >>> bin_spacing = np.mean(np.diff(bins))
| >>> plt.plot(x, weibull(x, 1., 5.) * bin_spacing * s.size, label='Weibull PDF')
| >>> plt.legend()
| >>> plt.show()
|
| zipf(self, a, size=None)
| zipf(a, size=None)
|
| Draw samples from a Zipf distribution.
|
| Samples are drawn from a Zipf distribution with specified parameter
| `a` > 1.
|
| The Zipf distribution (also known as the zeta distribution) is a
| discrete probability distribution that satisfies Zipf's law: the
| frequency of an item is inversely proportional to its rank in a
| frequency table.
|
| Parameters
| ----------
| a : float or array_like of floats
| Distribution parameter. Must be greater than 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``a`` is a scalar. Otherwise,
| ``np.array(a).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Zipf distribution.
|
| See Also
| --------
| scipy.stats.zipf : probability density function, distribution, or
| cumulative density function, etc.
|
| Notes
| -----
| The probability density for the Zipf distribution is
|
| .. math:: p(k) = \frac{k^{-a}}{\zeta(a)},
|
| for integers :math:`k \geq 1`, where :math:`\zeta` is the Riemann Zeta
| function.
|
| It is named for the American linguist George Kingsley Zipf, who noted
| that the frequency of any word in a sample of a language is inversely
| proportional to its rank in the frequency table.
|
| References
| ----------
| .. [1] Zipf, G. K., "Selected Studies of the Principle of Relative
| Frequency in Language," Cambridge, MA: Harvard Univ. Press,
| 1932.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> a = 4.0
| >>> n = 20000
| >>> rng = np.random.default_rng()
| >>> s = rng.zipf(a, size=n)
|
| Display the histogram of the samples, along with
| the expected histogram based on the probability
| density function:
|
| >>> import matplotlib.pyplot as plt
| >>> from scipy.special import zeta # doctest: +SKIP
|
| `bincount` provides a fast histogram for small integers.
|
| >>> count = np.bincount(s)
| >>> k = np.arange(1, s.max() + 1)
|
| >>> plt.bar(k, count[1:], alpha=0.5, label='sample count')
| >>> plt.plot(k, n*(k**-a)/zeta(a), 'k.-', alpha=0.5,
| ... label='expected count') # doctest: +SKIP
| >>> plt.semilogy()
| >>> plt.grid(alpha=0.4)
| >>> plt.legend()
| >>> plt.title(f'Zipf sample, a={a}, size={n}')
| >>> plt.show()
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| bit_generator
| Gets the bit generator instance used by the generator
|
| Returns
| -------
| bit_generator : BitGenerator
| The bit generator instance used by the generator
class MT19937(numpy.random.bit_generator.BitGenerator)
| MT19937(seed=None)
|
| Container for the Mersenne Twister pseudo-random number generator.
|
| Parameters
| ----------
| seed : {None, int, array_like[ints], SeedSequence}, optional
| A seed to initialize the `BitGenerator`. If None, then fresh,
| unpredictable entropy will be pulled from the OS. If an ``int`` or
| ``array_like[ints]`` is passed, then it will be passed to
| `SeedSequence` to derive the initial `BitGenerator` state. One may also
| pass in a `SeedSequence` instance.
|
| Attributes
| ----------
| lock: threading.Lock
| Lock instance that is shared so that the same bit git generator can
| be used in multiple Generators without corrupting the state. Code that
| generates values from a bit generator should hold the bit generator's
| lock.
|
| Notes
| -----
| `MT19937` provides a capsule containing function pointers that produce
| doubles, and unsigned 32 and 64- bit integers [1]_. These are not
| directly consumable in Python and must be consumed by a `Generator`
| or similar object that supports low-level access.
|
| The Python stdlib module "random" also contains a Mersenne Twister
| pseudo-random number generator.
|
| **State and Seeding**
|
| The `MT19937` state vector consists of a 624-element array of
| 32-bit unsigned integers plus a single integer value between 0 and 624
| that indexes the current position within the main array.
|
| The input seed is processed by `SeedSequence` to fill the whole state. The
| first element is reset such that only its most significant bit is set.
|
| **Parallel Features**
|
| The preferred way to use a BitGenerator in parallel applications is to use
| the `SeedSequence.spawn` method to obtain entropy values, and to use these
| to generate new BitGenerators:
|
| >>> from numpy.random import Generator, MT19937, SeedSequence
| >>> sg = SeedSequence(1234)
| >>> rg = [Generator(MT19937(s)) for s in sg.spawn(10)]
|
| Another method is to use `MT19937.jumped` which advances the state as-if
| :math:`2^{128}` random numbers have been generated ([1]_, [2]_). This
| allows the original sequence to be split so that distinct segments can be
| used in each worker process. All generators should be chained to ensure
| that the segments come from the same sequence.
|
| >>> from numpy.random import Generator, MT19937, SeedSequence
| >>> sg = SeedSequence(1234)
| >>> bit_generator = MT19937(sg)
| >>> rg = []
| >>> for _ in range(10):
| ... rg.append(Generator(bit_generator))
| ... # Chain the BitGenerators
| ... bit_generator = bit_generator.jumped()
|
| **Compatibility Guarantee**
|
| `MT19937` makes a guarantee that a fixed seed will always produce
| the same random integer stream.
|
| References
| ----------
| .. [1] Hiroshi Haramoto, Makoto Matsumoto, and Pierre L'Ecuyer, "A Fast
| Jump Ahead Algorithm for Linear Recurrences in a Polynomial Space",
| Sequences and Their Applications - SETA, 290--298, 2008.
| .. [2] Hiroshi Haramoto, Makoto Matsumoto, Takuji Nishimura, François
| Panneton, Pierre L'Ecuyer, "Efficient Jump Ahead for F2-Linear
| Random Number Generators", INFORMS JOURNAL ON COMPUTING, Vol. 20,
| No. 3, Summer 2008, pp. 385-390.
|
| Method resolution order:
| MT19937
| numpy.random.bit_generator.BitGenerator
| builtins.object
|
| Methods defined here:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_cython__(...)
|
| __setstate_cython__(...)
|
| jumped(self, jumps=1)
| jumped(jumps=1)
|
| Returns a new bit generator with the state jumped
|
| The state of the returned bit generator is jumped as-if
| 2**(128 * jumps) random numbers have been generated.
|
| Parameters
| ----------
| jumps : integer, positive
| Number of times to jump the state of the bit generator returned
|
| Returns
| -------
| bit_generator : MT19937
| New instance of generator jumped iter times
|
| Notes
| -----
| The jump step is computed using a modified version of Matsumoto's
| implementation of Horner's method. The step polynomial is precomputed
| to perform 2**128 steps. The jumped state has been verified to match
| the state produced using Matsumoto's original code.
|
| References
| ----------
| .. [1] Matsumoto, M, Generating multiple disjoint streams of
| pseudorandom number sequences. Accessed on: May 6, 2020.
| http://www.math.sci.hiroshima-u.ac.jp/m-mat/MT/JUMP/
| .. [2] Hiroshi Haramoto, Makoto Matsumoto, Takuji Nishimura, François
| Panneton, Pierre L'Ecuyer, "Efficient Jump Ahead for F2-Linear
| Random Number Generators", INFORMS JOURNAL ON COMPUTING, Vol. 20,
| No. 3, Summer 2008, pp. 385-390.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| state
| Get or set the PRNG state
|
| Returns
| -------
| state : dict
| Dictionary containing the information required to describe the
| state of the PRNG
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.random.bit_generator.BitGenerator:
|
| __getstate__(self)
|
| __reduce__(self)
|
| __setstate__(self, state_seed_seq)
|
| random_raw(self, size=None, output=True)
| random_raw(self, size=None)
|
| Return randoms as generated by the underlying BitGenerator
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| output : bool, optional
| Output values. Used for performance testing since the generated
| values are not returned.
|
| Returns
| -------
| out : uint or ndarray
| Drawn samples.
|
| Notes
| -----
| This method directly exposes the raw underlying pseudo-random
| number generator. All values are returned as unsigned 64-bit
| values irrespective of the number of bits produced by the PRNG.
|
| See the class docstring for the number of bits returned.
|
| spawn(self, n_children)
| spawn(n_children)
|
| Create new independent child bit generators.
|
| See :ref:`seedsequence-spawn` for additional notes on spawning
| children. Some bit generators also implement ``jumped``
| as a different approach for creating independent streams.
|
| .. versionadded:: 1.25.0
|
| Parameters
| ----------
| n_children : int
|
| Returns
| -------
| child_bit_generators : list of BitGenerators
|
| Raises
| ------
| TypeError
| When the underlying SeedSequence does not implement spawning.
|
| See Also
| --------
| random.Generator.spawn, random.SeedSequence.spawn :
| Equivalent method on the generator and seed sequence.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.random.bit_generator.BitGenerator:
|
| capsule
|
| cffi
| CFFI interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing CFFI wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| ctypes
| ctypes interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing ctypes wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| lock
|
| seed_seq
| Get the seed sequence used to initialize the bit generator.
|
| .. versionadded:: 1.25.0
|
| Returns
| -------
| seed_seq : ISeedSequence
| The SeedSequence object used to initialize the BitGenerator.
| This is normally a `np.random.SeedSequence` instance.
class PCG64(numpy.random.bit_generator.BitGenerator)
| PCG64(seed=None)
|
| BitGenerator for the PCG-64 pseudo-random number generator.
|
| Parameters
| ----------
| seed : {None, int, array_like[ints], SeedSequence}, optional
| A seed to initialize the `BitGenerator`. If None, then fresh,
| unpredictable entropy will be pulled from the OS. If an ``int`` or
| ``array_like[ints]`` is passed, then it will be passed to
| `SeedSequence` to derive the initial `BitGenerator` state. One may also
| pass in a `SeedSequence` instance.
|
| Notes
| -----
| PCG-64 is a 128-bit implementation of O'Neill's permutation congruential
| generator ([1]_, [2]_). PCG-64 has a period of :math:`2^{128}` and supports
| advancing an arbitrary number of steps as well as :math:`2^{127}` streams.
| The specific member of the PCG family that we use is PCG XSL RR 128/64
| as described in the paper ([2]_).
|
| `PCG64` provides a capsule containing function pointers that produce
| doubles, and unsigned 32 and 64- bit integers. These are not
| directly consumable in Python and must be consumed by a `Generator`
| or similar object that supports low-level access.
|
| Supports the method :meth:`advance` to advance the RNG an arbitrary number of
| steps. The state of the PCG-64 RNG is represented by 2 128-bit unsigned
| integers.
|
| **State and Seeding**
|
| The `PCG64` state vector consists of 2 unsigned 128-bit values,
| which are represented externally as Python ints. One is the state of the
| PRNG, which is advanced by a linear congruential generator (LCG). The
| second is a fixed odd increment used in the LCG.
|
| The input seed is processed by `SeedSequence` to generate both values. The
| increment is not independently settable.
|
| **Parallel Features**
|
| The preferred way to use a BitGenerator in parallel applications is to use
| the `SeedSequence.spawn` method to obtain entropy values, and to use these
| to generate new BitGenerators:
|
| >>> from numpy.random import Generator, PCG64, SeedSequence
| >>> sg = SeedSequence(1234)
| >>> rg = [Generator(PCG64(s)) for s in sg.spawn(10)]
|
| **Compatibility Guarantee**
|
| `PCG64` makes a guarantee that a fixed seed will always produce
| the same random integer stream.
|
| References
| ----------
| .. [1] `"PCG, A Family of Better Random Number Generators"
| <https://www.pcg-random.org/>`_
| .. [2] O'Neill, Melissa E. `"PCG: A Family of Simple Fast Space-Efficient
| Statistically Good Algorithms for Random Number Generation"
| <https://www.cs.hmc.edu/tr/hmc-cs-2014-0905.pdf>`_
|
| Method resolution order:
| PCG64
| numpy.random.bit_generator.BitGenerator
| builtins.object
|
| Methods defined here:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_cython__(...)
|
| __setstate_cython__(...)
|
| advance(self, delta)
| advance(delta)
|
| Advance the underlying RNG as-if delta draws have occurred.
|
| Parameters
| ----------
| delta : integer, positive
| Number of draws to advance the RNG. Must be less than the
| size state variable in the underlying RNG.
|
| Returns
| -------
| self : PCG64
| RNG advanced delta steps
|
| Notes
| -----
| Advancing a RNG updates the underlying RNG state as-if a given
| number of calls to the underlying RNG have been made. In general
| there is not a one-to-one relationship between the number output
| random values from a particular distribution and the number of
| draws from the core RNG. This occurs for two reasons:
|
| * The random values are simulated using a rejection-based method
| and so, on average, more than one value from the underlying
| RNG is required to generate an single draw.
| * The number of bits required to generate a simulated value
| differs from the number of bits generated by the underlying
| RNG. For example, two 16-bit integer values can be simulated
| from a single draw of a 32-bit RNG.
|
| Advancing the RNG state resets any pre-computed random numbers.
| This is required to ensure exact reproducibility.
|
| jumped(self, jumps=1)
| jumped(jumps=1)
|
| Returns a new bit generator with the state jumped.
|
| Jumps the state as-if jumps * 210306068529402873165736369884012333109
| random numbers have been generated.
|
| Parameters
| ----------
| jumps : integer, positive
| Number of times to jump the state of the bit generator returned
|
| Returns
| -------
| bit_generator : PCG64
| New instance of generator jumped iter times
|
| Notes
| -----
| The step size is phi-1 when multiplied by 2**128 where phi is the
| golden ratio.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| state
| Get or set the PRNG state
|
| Returns
| -------
| state : dict
| Dictionary containing the information required to describe the
| state of the PRNG
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.random.bit_generator.BitGenerator:
|
| __getstate__(self)
|
| __reduce__(self)
|
| __setstate__(self, state_seed_seq)
|
| random_raw(self, size=None, output=True)
| random_raw(self, size=None)
|
| Return randoms as generated by the underlying BitGenerator
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| output : bool, optional
| Output values. Used for performance testing since the generated
| values are not returned.
|
| Returns
| -------
| out : uint or ndarray
| Drawn samples.
|
| Notes
| -----
| This method directly exposes the raw underlying pseudo-random
| number generator. All values are returned as unsigned 64-bit
| values irrespective of the number of bits produced by the PRNG.
|
| See the class docstring for the number of bits returned.
|
| spawn(self, n_children)
| spawn(n_children)
|
| Create new independent child bit generators.
|
| See :ref:`seedsequence-spawn` for additional notes on spawning
| children. Some bit generators also implement ``jumped``
| as a different approach for creating independent streams.
|
| .. versionadded:: 1.25.0
|
| Parameters
| ----------
| n_children : int
|
| Returns
| -------
| child_bit_generators : list of BitGenerators
|
| Raises
| ------
| TypeError
| When the underlying SeedSequence does not implement spawning.
|
| See Also
| --------
| random.Generator.spawn, random.SeedSequence.spawn :
| Equivalent method on the generator and seed sequence.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.random.bit_generator.BitGenerator:
|
| capsule
|
| cffi
| CFFI interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing CFFI wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| ctypes
| ctypes interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing ctypes wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| lock
|
| seed_seq
| Get the seed sequence used to initialize the bit generator.
|
| .. versionadded:: 1.25.0
|
| Returns
| -------
| seed_seq : ISeedSequence
| The SeedSequence object used to initialize the BitGenerator.
| This is normally a `np.random.SeedSequence` instance.
class PCG64DXSM(numpy.random.bit_generator.BitGenerator)
| PCG64DXSM(seed=None)
|
| BitGenerator for the PCG-64 DXSM pseudo-random number generator.
|
| Parameters
| ----------
| seed : {None, int, array_like[ints], SeedSequence}, optional
| A seed to initialize the `BitGenerator`. If None, then fresh,
| unpredictable entropy will be pulled from the OS. If an ``int`` or
| ``array_like[ints]`` is passed, then it will be passed to
| `SeedSequence` to derive the initial `BitGenerator` state. One may also
| pass in a `SeedSequence` instance.
|
| Notes
| -----
| PCG-64 DXSM is a 128-bit implementation of O'Neill's permutation congruential
| generator ([1]_, [2]_). PCG-64 DXSM has a period of :math:`2^{128}` and supports
| advancing an arbitrary number of steps as well as :math:`2^{127}` streams.
| The specific member of the PCG family that we use is PCG CM DXSM 128/64. It
| differs from `PCG64` in that it uses the stronger DXSM output function,
| a 64-bit "cheap multiplier" in the LCG, and outputs from the state before
| advancing it rather than advance-then-output.
|
| `PCG64DXSM` provides a capsule containing function pointers that produce
| doubles, and unsigned 32 and 64- bit integers. These are not
| directly consumable in Python and must be consumed by a `Generator`
| or similar object that supports low-level access.
|
| Supports the method :meth:`advance` to advance the RNG an arbitrary number of
| steps. The state of the PCG-64 DXSM RNG is represented by 2 128-bit unsigned
| integers.
|
| **State and Seeding**
|
| The `PCG64DXSM` state vector consists of 2 unsigned 128-bit values,
| which are represented externally as Python ints. One is the state of the
| PRNG, which is advanced by a linear congruential generator (LCG). The
| second is a fixed odd increment used in the LCG.
|
| The input seed is processed by `SeedSequence` to generate both values. The
| increment is not independently settable.
|
| **Parallel Features**
|
| The preferred way to use a BitGenerator in parallel applications is to use
| the `SeedSequence.spawn` method to obtain entropy values, and to use these
| to generate new BitGenerators:
|
| >>> from numpy.random import Generator, PCG64DXSM, SeedSequence
| >>> sg = SeedSequence(1234)
| >>> rg = [Generator(PCG64DXSM(s)) for s in sg.spawn(10)]
|
| **Compatibility Guarantee**
|
| `PCG64DXSM` makes a guarantee that a fixed seed will always produce
| the same random integer stream.
|
| References
| ----------
| .. [1] `"PCG, A Family of Better Random Number Generators"
| <http://www.pcg-random.org/>`_
| .. [2] O'Neill, Melissa E. `"PCG: A Family of Simple Fast Space-Efficient
| Statistically Good Algorithms for Random Number Generation"
| <https://www.cs.hmc.edu/tr/hmc-cs-2014-0905.pdf>`_
|
| Method resolution order:
| PCG64DXSM
| numpy.random.bit_generator.BitGenerator
| builtins.object
|
| Methods defined here:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_cython__(...)
|
| __setstate_cython__(...)
|
| advance(self, delta)
| advance(delta)
|
| Advance the underlying RNG as-if delta draws have occurred.
|
| Parameters
| ----------
| delta : integer, positive
| Number of draws to advance the RNG. Must be less than the
| size state variable in the underlying RNG.
|
| Returns
| -------
| self : PCG64
| RNG advanced delta steps
|
| Notes
| -----
| Advancing a RNG updates the underlying RNG state as-if a given
| number of calls to the underlying RNG have been made. In general
| there is not a one-to-one relationship between the number output
| random values from a particular distribution and the number of
| draws from the core RNG. This occurs for two reasons:
|
| * The random values are simulated using a rejection-based method
| and so, on average, more than one value from the underlying
| RNG is required to generate an single draw.
| * The number of bits required to generate a simulated value
| differs from the number of bits generated by the underlying
| RNG. For example, two 16-bit integer values can be simulated
| from a single draw of a 32-bit RNG.
|
| Advancing the RNG state resets any pre-computed random numbers.
| This is required to ensure exact reproducibility.
|
| jumped(self, jumps=1)
| jumped(jumps=1)
|
| Returns a new bit generator with the state jumped.
|
| Jumps the state as-if jumps * 210306068529402873165736369884012333109
| random numbers have been generated.
|
| Parameters
| ----------
| jumps : integer, positive
| Number of times to jump the state of the bit generator returned
|
| Returns
| -------
| bit_generator : PCG64DXSM
| New instance of generator jumped iter times
|
| Notes
| -----
| The step size is phi-1 when multiplied by 2**128 where phi is the
| golden ratio.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| state
| Get or set the PRNG state
|
| Returns
| -------
| state : dict
| Dictionary containing the information required to describe the
| state of the PRNG
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.random.bit_generator.BitGenerator:
|
| __getstate__(self)
|
| __reduce__(self)
|
| __setstate__(self, state_seed_seq)
|
| random_raw(self, size=None, output=True)
| random_raw(self, size=None)
|
| Return randoms as generated by the underlying BitGenerator
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| output : bool, optional
| Output values. Used for performance testing since the generated
| values are not returned.
|
| Returns
| -------
| out : uint or ndarray
| Drawn samples.
|
| Notes
| -----
| This method directly exposes the raw underlying pseudo-random
| number generator. All values are returned as unsigned 64-bit
| values irrespective of the number of bits produced by the PRNG.
|
| See the class docstring for the number of bits returned.
|
| spawn(self, n_children)
| spawn(n_children)
|
| Create new independent child bit generators.
|
| See :ref:`seedsequence-spawn` for additional notes on spawning
| children. Some bit generators also implement ``jumped``
| as a different approach for creating independent streams.
|
| .. versionadded:: 1.25.0
|
| Parameters
| ----------
| n_children : int
|
| Returns
| -------
| child_bit_generators : list of BitGenerators
|
| Raises
| ------
| TypeError
| When the underlying SeedSequence does not implement spawning.
|
| See Also
| --------
| random.Generator.spawn, random.SeedSequence.spawn :
| Equivalent method on the generator and seed sequence.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.random.bit_generator.BitGenerator:
|
| capsule
|
| cffi
| CFFI interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing CFFI wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| ctypes
| ctypes interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing ctypes wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| lock
|
| seed_seq
| Get the seed sequence used to initialize the bit generator.
|
| .. versionadded:: 1.25.0
|
| Returns
| -------
| seed_seq : ISeedSequence
| The SeedSequence object used to initialize the BitGenerator.
| This is normally a `np.random.SeedSequence` instance.
class Philox(numpy.random.bit_generator.BitGenerator)
| Philox(seed=None, counter=None, key=None)
|
| Container for the Philox (4x64) pseudo-random number generator.
|
| Parameters
| ----------
| seed : {None, int, array_like[ints], SeedSequence}, optional
| A seed to initialize the `BitGenerator`. If None, then fresh,
| unpredictable entropy will be pulled from the OS. If an ``int`` or
| ``array_like[ints]`` is passed, then it will be passed to
| `SeedSequence` to derive the initial `BitGenerator` state. One may also
| pass in a `SeedSequence` instance.
| counter : {None, int, array_like}, optional
| Counter to use in the Philox state. Can be either
| a Python int (long in 2.x) in [0, 2**256) or a 4-element uint64 array.
| If not provided, the RNG is initialized at 0.
| key : {None, int, array_like}, optional
| Key to use in the Philox state. Unlike ``seed``, the value in key is
| directly set. Can be either a Python int in [0, 2**128) or a 2-element
| uint64 array. `key` and ``seed`` cannot both be used.
|
| Attributes
| ----------
| lock: threading.Lock
| Lock instance that is shared so that the same bit git generator can
| be used in multiple Generators without corrupting the state. Code that
| generates values from a bit generator should hold the bit generator's
| lock.
|
| Notes
| -----
| Philox is a 64-bit PRNG that uses a counter-based design based on weaker
| (and faster) versions of cryptographic functions [1]_. Instances using
| different values of the key produce independent sequences. Philox has a
| period of :math:`2^{256} - 1` and supports arbitrary advancing and jumping
| the sequence in increments of :math:`2^{128}`. These features allow
| multiple non-overlapping sequences to be generated.
|
| `Philox` provides a capsule containing function pointers that produce
| doubles, and unsigned 32 and 64- bit integers. These are not
| directly consumable in Python and must be consumed by a `Generator`
| or similar object that supports low-level access.
|
| **State and Seeding**
|
| The `Philox` state vector consists of a 256-bit value encoded as
| a 4-element uint64 array and a 128-bit value encoded as a 2-element uint64
| array. The former is a counter which is incremented by 1 for every 4 64-bit
| randoms produced. The second is a key which determined the sequence
| produced. Using different keys produces independent sequences.
|
| The input ``seed`` is processed by `SeedSequence` to generate the key. The
| counter is set to 0.
|
| Alternately, one can omit the ``seed`` parameter and set the ``key`` and
| ``counter`` directly.
|
| **Parallel Features**
|
| The preferred way to use a BitGenerator in parallel applications is to use
| the `SeedSequence.spawn` method to obtain entropy values, and to use these
| to generate new BitGenerators:
|
| >>> from numpy.random import Generator, Philox, SeedSequence
| >>> sg = SeedSequence(1234)
| >>> rg = [Generator(Philox(s)) for s in sg.spawn(10)]
|
| `Philox` can be used in parallel applications by calling the :meth:`jumped`
| method to advance the state as-if :math:`2^{128}` random numbers have
| been generated. Alternatively, :meth:`advance` can be used to advance the
| counter for any positive step in [0, 2**256). When using :meth:`jumped`, all
| generators should be chained to ensure that the segments come from the same
| sequence.
|
| >>> from numpy.random import Generator, Philox
| >>> bit_generator = Philox(1234)
| >>> rg = []
| >>> for _ in range(10):
| ... rg.append(Generator(bit_generator))
| ... bit_generator = bit_generator.jumped()
|
| Alternatively, `Philox` can be used in parallel applications by using
| a sequence of distinct keys where each instance uses different key.
|
| >>> key = 2**96 + 2**33 + 2**17 + 2**9
| >>> rg = [Generator(Philox(key=key+i)) for i in range(10)]
|
| **Compatibility Guarantee**
|
| `Philox` makes a guarantee that a fixed ``seed`` will always produce
| the same random integer stream.
|
| Examples
| --------
| >>> from numpy.random import Generator, Philox
| >>> rg = Generator(Philox(1234))
| >>> rg.standard_normal()
| 0.123 # random
|
| References
| ----------
| .. [1] John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw,
| "Parallel Random Numbers: As Easy as 1, 2, 3," Proceedings of
| the International Conference for High Performance Computing,
| Networking, Storage and Analysis (SC11), New York, NY: ACM, 2011.
|
| Method resolution order:
| Philox
| numpy.random.bit_generator.BitGenerator
| builtins.object
|
| Methods defined here:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_cython__(...)
|
| __setstate_cython__(...)
|
| advance(self, delta)
| advance(delta)
|
| Advance the underlying RNG as-if delta draws have occurred.
|
| Parameters
| ----------
| delta : integer, positive
| Number of draws to advance the RNG. Must be less than the
| size state variable in the underlying RNG.
|
| Returns
| -------
| self : Philox
| RNG advanced delta steps
|
| Notes
| -----
| Advancing a RNG updates the underlying RNG state as-if a given
| number of calls to the underlying RNG have been made. In general
| there is not a one-to-one relationship between the number output
| random values from a particular distribution and the number of
| draws from the core RNG. This occurs for two reasons:
|
| * The random values are simulated using a rejection-based method
| and so, on average, more than one value from the underlying
| RNG is required to generate an single draw.
| * The number of bits required to generate a simulated value
| differs from the number of bits generated by the underlying
| RNG. For example, two 16-bit integer values can be simulated
| from a single draw of a 32-bit RNG.
|
| Advancing the RNG state resets any pre-computed random numbers.
| This is required to ensure exact reproducibility.
|
| jumped(self, jumps=1)
| jumped(jumps=1)
|
| Returns a new bit generator with the state jumped
|
| The state of the returned bit generator is jumped as-if
| (2**128) * jumps random numbers have been generated.
|
| Parameters
| ----------
| jumps : integer, positive
| Number of times to jump the state of the bit generator returned
|
| Returns
| -------
| bit_generator : Philox
| New instance of generator jumped iter times
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| state
| Get or set the PRNG state
|
| Returns
| -------
| state : dict
| Dictionary containing the information required to describe the
| state of the PRNG
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.random.bit_generator.BitGenerator:
|
| __getstate__(self)
|
| __reduce__(self)
|
| __setstate__(self, state_seed_seq)
|
| random_raw(self, size=None, output=True)
| random_raw(self, size=None)
|
| Return randoms as generated by the underlying BitGenerator
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| output : bool, optional
| Output values. Used for performance testing since the generated
| values are not returned.
|
| Returns
| -------
| out : uint or ndarray
| Drawn samples.
|
| Notes
| -----
| This method directly exposes the raw underlying pseudo-random
| number generator. All values are returned as unsigned 64-bit
| values irrespective of the number of bits produced by the PRNG.
|
| See the class docstring for the number of bits returned.
|
| spawn(self, n_children)
| spawn(n_children)
|
| Create new independent child bit generators.
|
| See :ref:`seedsequence-spawn` for additional notes on spawning
| children. Some bit generators also implement ``jumped``
| as a different approach for creating independent streams.
|
| .. versionadded:: 1.25.0
|
| Parameters
| ----------
| n_children : int
|
| Returns
| -------
| child_bit_generators : list of BitGenerators
|
| Raises
| ------
| TypeError
| When the underlying SeedSequence does not implement spawning.
|
| See Also
| --------
| random.Generator.spawn, random.SeedSequence.spawn :
| Equivalent method on the generator and seed sequence.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.random.bit_generator.BitGenerator:
|
| capsule
|
| cffi
| CFFI interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing CFFI wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| ctypes
| ctypes interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing ctypes wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| lock
|
| seed_seq
| Get the seed sequence used to initialize the bit generator.
|
| .. versionadded:: 1.25.0
|
| Returns
| -------
| seed_seq : ISeedSequence
| The SeedSequence object used to initialize the BitGenerator.
| This is normally a `np.random.SeedSequence` instance.
class RandomState(builtins.object)
| RandomState(seed=None)
|
| Container for the slow Mersenne Twister pseudo-random number generator.
| Consider using a different BitGenerator with the Generator container
| instead.
|
| `RandomState` and `Generator` expose a number of methods for generating
| random numbers drawn from a variety of probability distributions. In
| addition to the distribution-specific arguments, each method takes a
| keyword argument `size` that defaults to ``None``. If `size` is ``None``,
| then a single value is generated and returned. If `size` is an integer,
| then a 1-D array filled with generated values is returned. If `size` is a
| tuple, then an array with that shape is filled and returned.
|
| **Compatibility Guarantee**
|
| A fixed bit generator using a fixed seed and a fixed series of calls to
| 'RandomState' methods using the same parameters will always produce the
| same results up to roundoff error except when the values were incorrect.
| `RandomState` is effectively frozen and will only receive updates that
| are required by changes in the internals of Numpy. More substantial
| changes, including algorithmic improvements, are reserved for
| `Generator`.
|
| Parameters
| ----------
| seed : {None, int, array_like, BitGenerator}, optional
| Random seed used to initialize the pseudo-random number generator or
| an instantized BitGenerator. If an integer or array, used as a seed for
| the MT19937 BitGenerator. Values can be any integer between 0 and
| 2**32 - 1 inclusive, an array (or other sequence) of such integers,
| or ``None`` (the default). If `seed` is ``None``, then the `MT19937`
| BitGenerator is initialized by reading data from ``/dev/urandom``
| (or the Windows analogue) if available or seed from the clock
| otherwise.
|
| Notes
| -----
| The Python stdlib module "random" also contains a Mersenne Twister
| pseudo-random number generator with a number of methods that are similar
| to the ones available in `RandomState`. `RandomState`, besides being
| NumPy-aware, has the advantage that it provides a much larger number
| of probability distributions to choose from.
|
| See Also
| --------
| Generator
| MT19937
| numpy.random.BitGenerator
|
| Methods defined here:
|
| __getstate__(self)
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce__(self)
|
| __repr__(...)
| Return repr(self).
|
| __setstate__(self, state)
|
| __str__(self, /)
| Return str(self).
|
| beta(self, a, b, size=None)
| beta(a, b, size=None)
|
| Draw samples from a Beta distribution.
|
| The Beta distribution is a special case of the Dirichlet distribution,
| and is related to the Gamma distribution. It has the probability
| distribution function
|
| .. math:: f(x; a,b) = \frac{1}{B(\alpha, \beta)} x^{\alpha - 1}
| (1 - x)^{\beta - 1},
|
| where the normalization, B, is the beta function,
|
| .. math:: B(\alpha, \beta) = \int_0^1 t^{\alpha - 1}
| (1 - t)^{\beta - 1} dt.
|
| It is often seen in Bayesian inference and order statistics.
|
| .. note::
| New code should use the `~numpy.random.Generator.beta`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
|
| Parameters
| ----------
| a : float or array_like of floats
| Alpha, positive (>0).
| b : float or array_like of floats
| Beta, positive (>0).
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``a`` and ``b`` are both scalars.
| Otherwise, ``np.broadcast(a, b).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized beta distribution.
|
| See Also
| --------
| random.Generator.beta: which should be used for new code.
|
| binomial(self, n, p, size=None)
| binomial(n, p, size=None)
|
| Draw samples from a binomial distribution.
|
| Samples are drawn from a binomial distribution with specified
| parameters, n trials and p probability of success where
| n an integer >= 0 and p is in the interval [0,1]. (n may be
| input as a float, but it is truncated to an integer in use)
|
| .. note::
| New code should use the `~numpy.random.Generator.binomial`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| n : int or array_like of ints
| Parameter of the distribution, >= 0. Floats are also accepted,
| but they will be truncated to integers.
| p : float or array_like of floats
| Parameter of the distribution, >= 0 and <=1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``n`` and ``p`` are both scalars.
| Otherwise, ``np.broadcast(n, p).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized binomial distribution, where
| each sample is equal to the number of successes over the n trials.
|
| See Also
| --------
| scipy.stats.binom : probability density function, distribution or
| cumulative density function, etc.
| random.Generator.binomial: which should be used for new code.
|
| Notes
| -----
| The probability density for the binomial distribution is
|
| .. math:: P(N) = \binom{n}{N}p^N(1-p)^{n-N},
|
| where :math:`n` is the number of trials, :math:`p` is the probability
| of success, and :math:`N` is the number of successes.
|
| When estimating the standard error of a proportion in a population by
| using a random sample, the normal distribution works well unless the
| product p*n <=5, where p = population proportion estimate, and n =
| number of samples, in which case the binomial distribution is used
| instead. For example, a sample of 15 people shows 4 who are left
| handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4,
| so the binomial distribution should be used in this case.
|
| References
| ----------
| .. [1] Dalgaard, Peter, "Introductory Statistics with R",
| Springer-Verlag, 2002.
| .. [2] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
| Fifth Edition, 2002.
| .. [3] Lentner, Marvin, "Elementary Applied Statistics", Bogden
| and Quigley, 1972.
| .. [4] Weisstein, Eric W. "Binomial Distribution." From MathWorld--A
| Wolfram Web Resource.
| https://mathworld.wolfram.com/BinomialDistribution.html
| .. [5] Wikipedia, "Binomial distribution",
| https://en.wikipedia.org/wiki/Binomial_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> n, p = 10, .5 # number of trials, probability of each trial
| >>> s = np.random.binomial(n, p, 1000)
| # result of flipping a coin 10 times, tested 1000 times.
|
| A real world example. A company drills 9 wild-cat oil exploration
| wells, each with an estimated probability of success of 0.1. All nine
| wells fail. What is the probability of that happening?
|
| Let's do 20,000 trials of the model, and count the number that
| generate zero positive results.
|
| >>> sum(np.random.binomial(9, 0.1, 20000) == 0)/20000.
| # answer = 0.38885, or 38%.
|
| bytes(self, length)
| bytes(length)
|
| Return random bytes.
|
| .. note::
| New code should use the `~numpy.random.Generator.bytes`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| length : int
| Number of random bytes.
|
| Returns
| -------
| out : bytes
| String of length `length`.
|
| See Also
| --------
| random.Generator.bytes: which should be used for new code.
|
| Examples
| --------
| >>> np.random.bytes(10)
| b' eh\x85\x022SZ\xbf\xa4' #random
|
| chisquare(self, df, size=None)
| chisquare(df, size=None)
|
| Draw samples from a chi-square distribution.
|
| When `df` independent random variables, each with standard normal
| distributions (mean 0, variance 1), are squared and summed, the
| resulting distribution is chi-square (see Notes). This distribution
| is often used in hypothesis testing.
|
| .. note::
| New code should use the `~numpy.random.Generator.chisquare`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| df : float or array_like of floats
| Number of degrees of freedom, must be > 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``df`` is a scalar. Otherwise,
| ``np.array(df).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized chi-square distribution.
|
| Raises
| ------
| ValueError
| When `df` <= 0 or when an inappropriate `size` (e.g. ``size=-1``)
| is given.
|
| See Also
| --------
| random.Generator.chisquare: which should be used for new code.
|
| Notes
| -----
| The variable obtained by summing the squares of `df` independent,
| standard normally distributed random variables:
|
| .. math:: Q = \sum_{i=0}^{\mathtt{df}} X^2_i
|
| is chi-square distributed, denoted
|
| .. math:: Q \sim \chi^2_k.
|
| The probability density function of the chi-squared distribution is
|
| .. math:: p(x) = \frac{(1/2)^{k/2}}{\Gamma(k/2)}
| x^{k/2 - 1} e^{-x/2},
|
| where :math:`\Gamma` is the gamma function,
|
| .. math:: \Gamma(x) = \int_0^{-\infty} t^{x - 1} e^{-t} dt.
|
| References
| ----------
| .. [1] NIST "Engineering Statistics Handbook"
| https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
|
| Examples
| --------
| >>> np.random.chisquare(2,4)
| array([ 1.89920014, 9.00867716, 3.13710533, 5.62318272]) # random
|
| choice(self, a, size=None, replace=True, p=None)
| choice(a, size=None, replace=True, p=None)
|
| Generates a random sample from a given 1-D array
|
| .. versionadded:: 1.7.0
|
| .. note::
| New code should use the `~numpy.random.Generator.choice`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| .. warning::
| This function uses the C-long dtype, which is 32bit on windows
| and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones).
| Since NumPy 2.0, NumPy's default integer is 32bit on 32bit platforms
| and 64bit on 64bit platforms.
|
|
| Parameters
| ----------
| a : 1-D array-like or int
| If an ndarray, a random sample is generated from its elements.
| If an int, the random sample is generated as if it were ``np.arange(a)``
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| replace : boolean, optional
| Whether the sample is with or without replacement. Default is True,
| meaning that a value of ``a`` can be selected multiple times.
| p : 1-D array-like, optional
| The probabilities associated with each entry in a.
| If not given, the sample assumes a uniform distribution over all
| entries in ``a``.
|
| Returns
| -------
| samples : single item or ndarray
| The generated random samples
|
| Raises
| ------
| ValueError
| If a is an int and less than zero, if a or p are not 1-dimensional,
| if a is an array-like of size 0, if p is not a vector of
| probabilities, if a and p have different lengths, or if
| replace=False and the sample size is greater than the population
| size
|
| See Also
| --------
| randint, shuffle, permutation
| random.Generator.choice: which should be used in new code
|
| Notes
| -----
| Setting user-specified probabilities through ``p`` uses a more general but less
| efficient sampler than the default. The general sampler produces a different sample
| than the optimized sampler even if each element of ``p`` is 1 / len(a).
|
| Sampling random rows from a 2-D array is not possible with this function,
| but is possible with `Generator.choice` through its ``axis`` keyword.
|
| Examples
| --------
| Generate a uniform random sample from np.arange(5) of size 3:
|
| >>> np.random.choice(5, 3)
| array([0, 3, 4]) # random
| >>> #This is equivalent to np.random.randint(0,5,3)
|
| Generate a non-uniform random sample from np.arange(5) of size 3:
|
| >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
| array([3, 3, 0]) # random
|
| Generate a uniform random sample from np.arange(5) of size 3 without
| replacement:
|
| >>> np.random.choice(5, 3, replace=False)
| array([3,1,0]) # random
| >>> #This is equivalent to np.random.permutation(np.arange(5))[:3]
|
| Generate a non-uniform random sample from np.arange(5) of size
| 3 without replacement:
|
| >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
| array([2, 3, 0]) # random
|
| Any of the above can be repeated with an arbitrary array-like
| instead of just integers. For instance:
|
| >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
| >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
| array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], # random
| dtype='<U11')
|
| dirichlet(self, alpha, size=None)
| dirichlet(alpha, size=None)
|
| Draw samples from the Dirichlet distribution.
|
| Draw `size` samples of dimension k from a Dirichlet distribution. A
| Dirichlet-distributed random variable can be seen as a multivariate
| generalization of a Beta distribution. The Dirichlet distribution
| is a conjugate prior of a multinomial distribution in Bayesian
| inference.
|
| .. note::
| New code should use the `~numpy.random.Generator.dirichlet`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| alpha : sequence of floats, length k
| Parameter of the distribution (length ``k`` for sample of
| length ``k``).
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| vector of length ``k`` is returned.
|
| Returns
| -------
| samples : ndarray,
| The drawn samples, of shape ``(size, k)``.
|
| Raises
| ------
| ValueError
| If any value in ``alpha`` is less than or equal to zero
|
| See Also
| --------
| random.Generator.dirichlet: which should be used for new code.
|
| Notes
| -----
| The Dirichlet distribution is a distribution over vectors
| :math:`x` that fulfil the conditions :math:`x_i>0` and
| :math:`\sum_{i=1}^k x_i = 1`.
|
| The probability density function :math:`p` of a
| Dirichlet-distributed random vector :math:`X` is
| proportional to
|
| .. math:: p(x) \propto \prod_{i=1}^{k}{x^{\alpha_i-1}_i},
|
| where :math:`\alpha` is a vector containing the positive
| concentration parameters.
|
| The method uses the following property for computation: let :math:`Y`
| be a random vector which has components that follow a standard gamma
| distribution, then :math:`X = \frac{1}{\sum_{i=1}^k{Y_i}} Y`
| is Dirichlet-distributed
|
| References
| ----------
| .. [1] David McKay, "Information Theory, Inference and Learning
| Algorithms," chapter 23,
| https://www.inference.org.uk/mackay/itila/
| .. [2] Wikipedia, "Dirichlet distribution",
| https://en.wikipedia.org/wiki/Dirichlet_distribution
|
| Examples
| --------
| Taking an example cited in Wikipedia, this distribution can be used if
| one wanted to cut strings (each of initial length 1.0) into K pieces
| with different lengths, where each piece had, on average, a designated
| average length, but allowing some variation in the relative sizes of
| the pieces.
|
| >>> s = np.random.dirichlet((10, 5, 3), 20).transpose()
|
| >>> import matplotlib.pyplot as plt
| >>> plt.barh(range(20), s[0])
| >>> plt.barh(range(20), s[1], left=s[0], color='g')
| >>> plt.barh(range(20), s[2], left=s[0]+s[1], color='r')
| >>> plt.title("Lengths of Strings")
|
| exponential(self, scale=1.0, size=None)
| exponential(scale=1.0, size=None)
|
| Draw samples from an exponential distribution.
|
| Its probability density function is
|
| .. math:: f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}),
|
| for ``x > 0`` and 0 elsewhere. :math:`\beta` is the scale parameter,
| which is the inverse of the rate parameter :math:`\lambda = 1/\beta`.
| The rate parameter is an alternative, widely used parameterization
| of the exponential distribution [3]_.
|
| The exponential distribution is a continuous analogue of the
| geometric distribution. It describes many common situations, such as
| the size of raindrops measured over many rainstorms [1]_, or the time
| between page requests to Wikipedia [2]_.
|
| .. note::
| New code should use the `~numpy.random.Generator.exponential`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| scale : float or array_like of floats
| The scale parameter, :math:`\beta = 1/\lambda`. Must be
| non-negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``scale`` is a scalar. Otherwise,
| ``np.array(scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized exponential distribution.
|
| Examples
| --------
| A real world example: Assume a company has 10000 customer support
| agents and the average time between customer calls is 4 minutes.
|
| >>> n = 10000
| >>> time_between_calls = np.random.default_rng().exponential(scale=4, size=n)
|
| What is the probability that a customer will call in the next
| 4 to 5 minutes?
|
| >>> x = ((time_between_calls < 5).sum())/n
| >>> y = ((time_between_calls < 4).sum())/n
| >>> x-y
| 0.08 # may vary
|
| See Also
| --------
| random.Generator.exponential: which should be used for new code.
|
| References
| ----------
| .. [1] Peyton Z. Peebles Jr., "Probability, Random Variables and
| Random Signal Principles", 4th ed, 2001, p. 57.
| .. [2] Wikipedia, "Poisson process",
| https://en.wikipedia.org/wiki/Poisson_process
| .. [3] Wikipedia, "Exponential distribution",
| https://en.wikipedia.org/wiki/Exponential_distribution
|
| f(self, dfnum, dfden, size=None)
| f(dfnum, dfden, size=None)
|
| Draw samples from an F distribution.
|
| Samples are drawn from an F distribution with specified parameters,
| `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of
| freedom in denominator), where both parameters must be greater than
| zero.
|
| The random variate of the F distribution (also known as the
| Fisher distribution) is a continuous probability distribution
| that arises in ANOVA tests, and is the ratio of two chi-square
| variates.
|
| .. note::
| New code should use the `~numpy.random.Generator.f`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| dfnum : float or array_like of floats
| Degrees of freedom in numerator, must be > 0.
| dfden : float or array_like of float
| Degrees of freedom in denominator, must be > 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``dfnum`` and ``dfden`` are both scalars.
| Otherwise, ``np.broadcast(dfnum, dfden).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Fisher distribution.
|
| See Also
| --------
| scipy.stats.f : probability density function, distribution or
| cumulative density function, etc.
| random.Generator.f: which should be used for new code.
|
| Notes
| -----
| The F statistic is used to compare in-group variances to between-group
| variances. Calculating the distribution depends on the sampling, and
| so it is a function of the respective degrees of freedom in the
| problem. The variable `dfnum` is the number of samples minus one, the
| between-groups degrees of freedom, while `dfden` is the within-groups
| degrees of freedom, the sum of the number of samples in each group
| minus the number of groups.
|
| References
| ----------
| .. [1] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
| Fifth Edition, 2002.
| .. [2] Wikipedia, "F-distribution",
| https://en.wikipedia.org/wiki/F-distribution
|
| Examples
| --------
| An example from Glantz[1], pp 47-40:
|
| Two groups, children of diabetics (25 people) and children from people
| without diabetes (25 controls). Fasting blood glucose was measured,
| case group had a mean value of 86.1, controls had a mean value of
| 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these
| data consistent with the null hypothesis that the parents diabetic
| status does not affect their children's blood glucose levels?
| Calculating the F statistic from the data gives a value of 36.01.
|
| Draw samples from the distribution:
|
| >>> dfnum = 1. # between group degrees of freedom
| >>> dfden = 48. # within groups degrees of freedom
| >>> s = np.random.f(dfnum, dfden, 1000)
|
| The lower bound for the top 1% of the samples is :
|
| >>> np.sort(s)[-10]
| 7.61988120985 # random
|
| So there is about a 1% chance that the F statistic will exceed 7.62,
| the measured value is 36, so the null hypothesis is rejected at the 1%
| level.
|
| gamma(self, shape, scale=1.0, size=None)
| gamma(shape, scale=1.0, size=None)
|
| Draw samples from a Gamma distribution.
|
| Samples are drawn from a Gamma distribution with specified parameters,
| `shape` (sometimes designated "k") and `scale` (sometimes designated
| "theta"), where both parameters are > 0.
|
| .. note::
| New code should use the `~numpy.random.Generator.gamma`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| shape : float or array_like of floats
| The shape of the gamma distribution. Must be non-negative.
| scale : float or array_like of floats, optional
| The scale of the gamma distribution. Must be non-negative.
| Default is equal to 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``shape`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(shape, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized gamma distribution.
|
| See Also
| --------
| scipy.stats.gamma : probability density function, distribution or
| cumulative density function, etc.
| random.Generator.gamma: which should be used for new code.
|
| Notes
| -----
| The probability density for the Gamma distribution is
|
| .. math:: p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},
|
| where :math:`k` is the shape and :math:`\theta` the scale,
| and :math:`\Gamma` is the Gamma function.
|
| The Gamma distribution is often used to model the times to failure of
| electronic components, and arises naturally in processes for which the
| waiting times between Poisson distributed events are relevant.
|
| References
| ----------
| .. [1] Weisstein, Eric W. "Gamma Distribution." From MathWorld--A
| Wolfram Web Resource.
| https://mathworld.wolfram.com/GammaDistribution.html
| .. [2] Wikipedia, "Gamma distribution",
| https://en.wikipedia.org/wiki/Gamma_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> shape, scale = 2., 2. # mean=4, std=2*sqrt(2)
| >>> s = np.random.gamma(shape, scale, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> import scipy.special as sps # doctest: +SKIP
| >>> count, bins, ignored = plt.hist(s, 50, density=True)
| >>> y = bins**(shape-1)*(np.exp(-bins/scale) / # doctest: +SKIP
| ... (sps.gamma(shape)*scale**shape))
| >>> plt.plot(bins, y, linewidth=2, color='r') # doctest: +SKIP
| >>> plt.show()
|
| geometric(self, p, size=None)
| geometric(p, size=None)
|
| Draw samples from the geometric distribution.
|
| Bernoulli trials are experiments with one of two outcomes:
| success or failure (an example of such an experiment is flipping
| a coin). The geometric distribution models the number of trials
| that must be run in order to achieve success. It is therefore
| supported on the positive integers, ``k = 1, 2, ...``.
|
| The probability mass function of the geometric distribution is
|
| .. math:: f(k) = (1 - p)^{k - 1} p
|
| where `p` is the probability of success of an individual trial.
|
| .. note::
| New code should use the `~numpy.random.Generator.geometric`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| p : float or array_like of floats
| The probability of success of an individual trial.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``p`` is a scalar. Otherwise,
| ``np.array(p).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized geometric distribution.
|
| See Also
| --------
| random.Generator.geometric: which should be used for new code.
|
| Examples
| --------
| Draw ten thousand values from the geometric distribution,
| with the probability of an individual success equal to 0.35:
|
| >>> z = np.random.geometric(p=0.35, size=10000)
|
| How many trials succeeded after a single run?
|
| >>> (z == 1).sum() / 10000.
| 0.34889999999999999 #random
|
| get_state(self, legacy=True)
| get_state(legacy=True)
|
| Return a tuple representing the internal state of the generator.
|
| For more details, see `set_state`.
|
| Parameters
| ----------
| legacy : bool, optional
| Flag indicating to return a legacy tuple state when the BitGenerator
| is MT19937, instead of a dict. Raises ValueError if the underlying
| bit generator is not an instance of MT19937.
|
| Returns
| -------
| out : {tuple(str, ndarray of 624 uints, int, int, float), dict}
| If legacy is True, the returned tuple has the following items:
|
| 1. the string 'MT19937'.
| 2. a 1-D array of 624 unsigned integer keys.
| 3. an integer ``pos``.
| 4. an integer ``has_gauss``.
| 5. a float ``cached_gaussian``.
|
| If `legacy` is False, or the BitGenerator is not MT19937, then
| state is returned as a dictionary.
|
| See Also
| --------
| set_state
|
| Notes
| -----
| `set_state` and `get_state` are not needed to work with any of the
| random distributions in NumPy. If the internal state is manually altered,
| the user should know exactly what he/she is doing.
|
| gumbel(self, loc=0.0, scale=1.0, size=None)
| gumbel(loc=0.0, scale=1.0, size=None)
|
| Draw samples from a Gumbel distribution.
|
| Draw samples from a Gumbel distribution with specified location and
| scale. For more information on the Gumbel distribution, see
| Notes and References below.
|
| .. note::
| New code should use the `~numpy.random.Generator.gumbel`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| loc : float or array_like of floats, optional
| The location of the mode of the distribution. Default is 0.
| scale : float or array_like of floats, optional
| The scale parameter of the distribution. Default is 1. Must be non-
| negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``loc`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Gumbel distribution.
|
| See Also
| --------
| scipy.stats.gumbel_l
| scipy.stats.gumbel_r
| scipy.stats.genextreme
| weibull
| random.Generator.gumbel: which should be used for new code.
|
| Notes
| -----
| The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme
| Value Type I) distribution is one of a class of Generalized Extreme
| Value (GEV) distributions used in modeling extreme value problems.
| The Gumbel is a special case of the Extreme Value Type I distribution
| for maximums from distributions with "exponential-like" tails.
|
| The probability density for the Gumbel distribution is
|
| .. math:: p(x) = \frac{e^{-(x - \mu)/ \beta}}{\beta} e^{ -e^{-(x - \mu)/
| \beta}},
|
| where :math:`\mu` is the mode, a location parameter, and
| :math:`\beta` is the scale parameter.
|
| The Gumbel (named for German mathematician Emil Julius Gumbel) was used
| very early in the hydrology literature, for modeling the occurrence of
| flood events. It is also used for modeling maximum wind speed and
| rainfall rates. It is a "fat-tailed" distribution - the probability of
| an event in the tail of the distribution is larger than if one used a
| Gaussian, hence the surprisingly frequent occurrence of 100-year
| floods. Floods were initially modeled as a Gaussian process, which
| underestimated the frequency of extreme events.
|
| It is one of a class of extreme value distributions, the Generalized
| Extreme Value (GEV) distributions, which also includes the Weibull and
| Frechet.
|
| The function has a mean of :math:`\mu + 0.57721\beta` and a variance
| of :math:`\frac{\pi^2}{6}\beta^2`.
|
| References
| ----------
| .. [1] Gumbel, E. J., "Statistics of Extremes,"
| New York: Columbia University Press, 1958.
| .. [2] Reiss, R.-D. and Thomas, M., "Statistical Analysis of Extreme
| Values from Insurance, Finance, Hydrology and Other Fields,"
| Basel: Birkhauser Verlag, 2001.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> mu, beta = 0, 0.1 # location and scale
| >>> s = np.random.gumbel(mu, beta, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, ignored = plt.hist(s, 30, density=True)
| >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
| ... * np.exp( -np.exp( -(bins - mu) /beta) ),
| ... linewidth=2, color='r')
| >>> plt.show()
|
| Show how an extreme value distribution can arise from a Gaussian process
| and compare to a Gaussian:
|
| >>> means = []
| >>> maxima = []
| >>> for i in range(0,1000) :
| ... a = np.random.normal(mu, beta, 1000)
| ... means.append(a.mean())
| ... maxima.append(a.max())
| >>> count, bins, ignored = plt.hist(maxima, 30, density=True)
| >>> beta = np.std(maxima) * np.sqrt(6) / np.pi
| >>> mu = np.mean(maxima) - 0.57721*beta
| >>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
| ... * np.exp(-np.exp(-(bins - mu)/beta)),
| ... linewidth=2, color='r')
| >>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi))
| ... * np.exp(-(bins - mu)**2 / (2 * beta**2)),
| ... linewidth=2, color='g')
| >>> plt.show()
|
| hypergeometric(self, ngood, nbad, nsample, size=None)
| hypergeometric(ngood, nbad, nsample, size=None)
|
| Draw samples from a Hypergeometric distribution.
|
| Samples are drawn from a hypergeometric distribution with specified
| parameters, `ngood` (ways to make a good selection), `nbad` (ways to make
| a bad selection), and `nsample` (number of items sampled, which is less
| than or equal to the sum ``ngood + nbad``).
|
| .. note::
| New code should use the
| `~numpy.random.Generator.hypergeometric`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| ngood : int or array_like of ints
| Number of ways to make a good selection. Must be nonnegative.
| nbad : int or array_like of ints
| Number of ways to make a bad selection. Must be nonnegative.
| nsample : int or array_like of ints
| Number of items sampled. Must be at least 1 and at most
| ``ngood + nbad``.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if `ngood`, `nbad`, and `nsample`
| are all scalars. Otherwise, ``np.broadcast(ngood, nbad, nsample).size``
| samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized hypergeometric distribution. Each
| sample is the number of good items within a randomly selected subset of
| size `nsample` taken from a set of `ngood` good items and `nbad` bad items.
|
| See Also
| --------
| scipy.stats.hypergeom : probability density function, distribution or
| cumulative density function, etc.
| random.Generator.hypergeometric: which should be used for new code.
|
| Notes
| -----
| The probability density for the Hypergeometric distribution is
|
| .. math:: P(x) = \frac{\binom{g}{x}\binom{b}{n-x}}{\binom{g+b}{n}},
|
| where :math:`0 \le x \le n` and :math:`n-b \le x \le g`
|
| for P(x) the probability of ``x`` good results in the drawn sample,
| g = `ngood`, b = `nbad`, and n = `nsample`.
|
| Consider an urn with black and white marbles in it, `ngood` of them
| are black and `nbad` are white. If you draw `nsample` balls without
| replacement, then the hypergeometric distribution describes the
| distribution of black balls in the drawn sample.
|
| Note that this distribution is very similar to the binomial
| distribution, except that in this case, samples are drawn without
| replacement, whereas in the Binomial case samples are drawn with
| replacement (or the sample space is infinite). As the sample space
| becomes large, this distribution approaches the binomial.
|
| References
| ----------
| .. [1] Lentner, Marvin, "Elementary Applied Statistics", Bogden
| and Quigley, 1972.
| .. [2] Weisstein, Eric W. "Hypergeometric Distribution." From
| MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/HypergeometricDistribution.html
| .. [3] Wikipedia, "Hypergeometric distribution",
| https://en.wikipedia.org/wiki/Hypergeometric_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> ngood, nbad, nsamp = 100, 2, 10
| # number of good, number of bad, and number of samples
| >>> s = np.random.hypergeometric(ngood, nbad, nsamp, 1000)
| >>> from matplotlib.pyplot import hist
| >>> hist(s)
| # note that it is very unlikely to grab both bad items
|
| Suppose you have an urn with 15 white and 15 black marbles.
| If you pull 15 marbles at random, how likely is it that
| 12 or more of them are one color?
|
| >>> s = np.random.hypergeometric(15, 15, 15, 100000)
| >>> sum(s>=12)/100000. + sum(s<=3)/100000.
| # answer = 0.003 ... pretty unlikely!
|
| laplace(self, loc=0.0, scale=1.0, size=None)
| laplace(loc=0.0, scale=1.0, size=None)
|
| Draw samples from the Laplace or double exponential distribution with
| specified location (or mean) and scale (decay).
|
| The Laplace distribution is similar to the Gaussian/normal distribution,
| but is sharper at the peak and has fatter tails. It represents the
| difference between two independent, identically distributed exponential
| random variables.
|
| .. note::
| New code should use the `~numpy.random.Generator.laplace`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| loc : float or array_like of floats, optional
| The position, :math:`\mu`, of the distribution peak. Default is 0.
| scale : float or array_like of floats, optional
| :math:`\lambda`, the exponential decay. Default is 1. Must be non-
| negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``loc`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Laplace distribution.
|
| See Also
| --------
| random.Generator.laplace: which should be used for new code.
|
| Notes
| -----
| It has the probability density function
|
| .. math:: f(x; \mu, \lambda) = \frac{1}{2\lambda}
| \exp\left(-\frac{|x - \mu|}{\lambda}\right).
|
| The first law of Laplace, from 1774, states that the frequency
| of an error can be expressed as an exponential function of the
| absolute magnitude of the error, which leads to the Laplace
| distribution. For many problems in economics and health
| sciences, this distribution seems to model the data better
| than the standard Gaussian distribution.
|
| References
| ----------
| .. [1] Abramowitz, M. and Stegun, I. A. (Eds.). "Handbook of
| Mathematical Functions with Formulas, Graphs, and Mathematical
| Tables, 9th printing," New York: Dover, 1972.
| .. [2] Kotz, Samuel, et. al. "The Laplace Distribution and
| Generalizations, " Birkhauser, 2001.
| .. [3] Weisstein, Eric W. "Laplace Distribution."
| From MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/LaplaceDistribution.html
| .. [4] Wikipedia, "Laplace distribution",
| https://en.wikipedia.org/wiki/Laplace_distribution
|
| Examples
| --------
| Draw samples from the distribution
|
| >>> loc, scale = 0., 1.
| >>> s = np.random.laplace(loc, scale, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, ignored = plt.hist(s, 30, density=True)
| >>> x = np.arange(-8., 8., .01)
| >>> pdf = np.exp(-abs(x-loc)/scale)/(2.*scale)
| >>> plt.plot(x, pdf)
|
| Plot Gaussian for comparison:
|
| >>> g = (1/(scale * np.sqrt(2 * np.pi)) *
| ... np.exp(-(x - loc)**2 / (2 * scale**2)))
| >>> plt.plot(x,g)
|
| logistic(self, loc=0.0, scale=1.0, size=None)
| logistic(loc=0.0, scale=1.0, size=None)
|
| Draw samples from a logistic distribution.
|
| Samples are drawn from a logistic distribution with specified
| parameters, loc (location or mean, also median), and scale (>0).
|
| .. note::
| New code should use the `~numpy.random.Generator.logistic`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| loc : float or array_like of floats, optional
| Parameter of the distribution. Default is 0.
| scale : float or array_like of floats, optional
| Parameter of the distribution. Must be non-negative.
| Default is 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``loc`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized logistic distribution.
|
| See Also
| --------
| scipy.stats.logistic : probability density function, distribution or
| cumulative density function, etc.
| random.Generator.logistic: which should be used for new code.
|
| Notes
| -----
| The probability density for the Logistic distribution is
|
| .. math:: P(x) = P(x) = \frac{e^{-(x-\mu)/s}}{s(1+e^{-(x-\mu)/s})^2},
|
| where :math:`\mu` = location and :math:`s` = scale.
|
| The Logistic distribution is used in Extreme Value problems where it
| can act as a mixture of Gumbel distributions, in Epidemiology, and by
| the World Chess Federation (FIDE) where it is used in the Elo ranking
| system, assuming the performance of each player is a logistically
| distributed random variable.
|
| References
| ----------
| .. [1] Reiss, R.-D. and Thomas M. (2001), "Statistical Analysis of
| Extreme Values, from Insurance, Finance, Hydrology and Other
| Fields," Birkhauser Verlag, Basel, pp 132-133.
| .. [2] Weisstein, Eric W. "Logistic Distribution." From
| MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/LogisticDistribution.html
| .. [3] Wikipedia, "Logistic-distribution",
| https://en.wikipedia.org/wiki/Logistic_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> loc, scale = 10, 1
| >>> s = np.random.logistic(loc, scale, 10000)
| >>> import matplotlib.pyplot as plt
| >>> count, bins, ignored = plt.hist(s, bins=50)
|
| # plot against distribution
|
| >>> def logist(x, loc, scale):
| ... return np.exp((loc-x)/scale)/(scale*(1+np.exp((loc-x)/scale))**2)
| >>> lgst_val = logist(bins, loc, scale)
| >>> plt.plot(bins, lgst_val * count.max() / lgst_val.max())
| >>> plt.show()
|
| lognormal(self, mean=0.0, sigma=1.0, size=None)
| lognormal(mean=0.0, sigma=1.0, size=None)
|
| Draw samples from a log-normal distribution.
|
| Draw samples from a log-normal distribution with specified mean,
| standard deviation, and array shape. Note that the mean and standard
| deviation are not the values for the distribution itself, but of the
| underlying normal distribution it is derived from.
|
| .. note::
| New code should use the `~numpy.random.Generator.lognormal`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| mean : float or array_like of floats, optional
| Mean value of the underlying normal distribution. Default is 0.
| sigma : float or array_like of floats, optional
| Standard deviation of the underlying normal distribution. Must be
| non-negative. Default is 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``mean`` and ``sigma`` are both scalars.
| Otherwise, ``np.broadcast(mean, sigma).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized log-normal distribution.
|
| See Also
| --------
| scipy.stats.lognorm : probability density function, distribution,
| cumulative density function, etc.
| random.Generator.lognormal: which should be used for new code.
|
| Notes
| -----
| A variable `x` has a log-normal distribution if `log(x)` is normally
| distributed. The probability density function for the log-normal
| distribution is:
|
| .. math:: p(x) = \frac{1}{\sigma x \sqrt{2\pi}}
| e^{(-\frac{(ln(x)-\mu)^2}{2\sigma^2})}
|
| where :math:`\mu` is the mean and :math:`\sigma` is the standard
| deviation of the normally distributed logarithm of the variable.
| A log-normal distribution results if a random variable is the *product*
| of a large number of independent, identically-distributed variables in
| the same way that a normal distribution results if the variable is the
| *sum* of a large number of independent, identically-distributed
| variables.
|
| References
| ----------
| .. [1] Limpert, E., Stahel, W. A., and Abbt, M., "Log-normal
| Distributions across the Sciences: Keys and Clues,"
| BioScience, Vol. 51, No. 5, May, 2001.
| https://stat.ethz.ch/~stahel/lognormal/bioscience.pdf
| .. [2] Reiss, R.D. and Thomas, M., "Statistical Analysis of Extreme
| Values," Basel: Birkhauser Verlag, 2001, pp. 31-32.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> mu, sigma = 3., 1. # mean and standard deviation
| >>> s = np.random.lognormal(mu, sigma, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, ignored = plt.hist(s, 100, density=True, align='mid')
|
| >>> x = np.linspace(min(bins), max(bins), 10000)
| >>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
| ... / (x * sigma * np.sqrt(2 * np.pi)))
|
| >>> plt.plot(x, pdf, linewidth=2, color='r')
| >>> plt.axis('tight')
| >>> plt.show()
|
| Demonstrate that taking the products of random samples from a uniform
| distribution can be fit well by a log-normal probability density
| function.
|
| >>> # Generate a thousand samples: each is the product of 100 random
| >>> # values, drawn from a normal distribution.
| >>> b = []
| >>> for i in range(1000):
| ... a = 10. + np.random.standard_normal(100)
| ... b.append(np.prod(a))
|
| >>> b = np.array(b) / np.min(b) # scale values to be positive
| >>> count, bins, ignored = plt.hist(b, 100, density=True, align='mid')
| >>> sigma = np.std(np.log(b))
| >>> mu = np.mean(np.log(b))
|
| >>> x = np.linspace(min(bins), max(bins), 10000)
| >>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
| ... / (x * sigma * np.sqrt(2 * np.pi)))
|
| >>> plt.plot(x, pdf, color='r', linewidth=2)
| >>> plt.show()
|
| logseries(self, p, size=None)
| logseries(p, size=None)
|
| Draw samples from a logarithmic series distribution.
|
| Samples are drawn from a log series distribution with specified
| shape parameter, 0 <= ``p`` < 1.
|
| .. note::
| New code should use the `~numpy.random.Generator.logseries`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| p : float or array_like of floats
| Shape parameter for the distribution. Must be in the range [0, 1).
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``p`` is a scalar. Otherwise,
| ``np.array(p).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized logarithmic series distribution.
|
| See Also
| --------
| scipy.stats.logser : probability density function, distribution or
| cumulative density function, etc.
| random.Generator.logseries: which should be used for new code.
|
| Notes
| -----
| The probability density for the Log Series distribution is
|
| .. math:: P(k) = \frac{-p^k}{k \ln(1-p)},
|
| where p = probability.
|
| The log series distribution is frequently used to represent species
| richness and occurrence, first proposed by Fisher, Corbet, and
| Williams in 1943 [2]. It may also be used to model the numbers of
| occupants seen in cars [3].
|
| References
| ----------
| .. [1] Buzas, Martin A.; Culver, Stephen J., Understanding regional
| species diversity through the log series distribution of
| occurrences: BIODIVERSITY RESEARCH Diversity & Distributions,
| Volume 5, Number 5, September 1999 , pp. 187-195(9).
| .. [2] Fisher, R.A,, A.S. Corbet, and C.B. Williams. 1943. The
| relation between the number of species and the number of
| individuals in a random sample of an animal population.
| Journal of Animal Ecology, 12:42-58.
| .. [3] D. J. Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small
| Data Sets, CRC Press, 1994.
| .. [4] Wikipedia, "Logarithmic distribution",
| https://en.wikipedia.org/wiki/Logarithmic_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> a = .6
| >>> s = np.random.logseries(a, 10000)
| >>> import matplotlib.pyplot as plt
| >>> count, bins, ignored = plt.hist(s)
|
| # plot against distribution
|
| >>> def logseries(k, p):
| ... return -p**k/(k*np.log(1-p))
| >>> plt.plot(bins, logseries(bins, a)*count.max()/
| ... logseries(bins, a).max(), 'r')
| >>> plt.show()
|
| multinomial(self, n, pvals, size=None)
| multinomial(n, pvals, size=None)
|
| Draw samples from a multinomial distribution.
|
| The multinomial distribution is a multivariate generalization of the
| binomial distribution. Take an experiment with one of ``p``
| possible outcomes. An example of such an experiment is throwing a dice,
| where the outcome can be 1 through 6. Each sample drawn from the
| distribution represents `n` such experiments. Its values,
| ``X_i = [X_0, X_1, ..., X_p]``, represent the number of times the
| outcome was ``i``.
|
| .. note::
| New code should use the `~numpy.random.Generator.multinomial`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| .. warning::
| This function defaults to the C-long dtype, which is 32bit on windows
| and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones).
| Since NumPy 2.0, NumPy's default integer is 32bit on 32bit platforms
| and 64bit on 64bit platforms.
|
|
| Parameters
| ----------
| n : int
| Number of experiments.
| pvals : sequence of floats, length p
| Probabilities of each of the ``p`` different outcomes. These
| must sum to 1 (however, the last element is always assumed to
| account for the remaining probability, as long as
| ``sum(pvals[:-1]) <= 1)``.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
|
| Returns
| -------
| out : ndarray
| The drawn samples, of shape *size*, if that was provided. If not,
| the shape is ``(N,)``.
|
| In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
| value drawn from the distribution.
|
| See Also
| --------
| random.Generator.multinomial: which should be used for new code.
|
| Examples
| --------
| Throw a dice 20 times:
|
| >>> np.random.multinomial(20, [1/6.]*6, size=1)
| array([[4, 1, 7, 5, 2, 1]]) # random
|
| It landed 4 times on 1, once on 2, etc.
|
| Now, throw the dice 20 times, and 20 times again:
|
| >>> np.random.multinomial(20, [1/6.]*6, size=2)
| array([[3, 4, 3, 3, 4, 3], # random
| [2, 4, 3, 4, 0, 7]])
|
| For the first run, we threw 3 times 1, 4 times 2, etc. For the second,
| we threw 2 times 1, 4 times 2, etc.
|
| A loaded die is more likely to land on number 6:
|
| >>> np.random.multinomial(100, [1/7.]*5 + [2/7.])
| array([11, 16, 14, 17, 16, 26]) # random
|
| The probability inputs should be normalized. As an implementation
| detail, the value of the last entry is ignored and assumed to take
| up any leftover probability mass, but this should not be relied on.
| A biased coin which has twice as much weight on one side as on the
| other should be sampled like so:
|
| >>> np.random.multinomial(100, [1.0 / 3, 2.0 / 3]) # RIGHT
| array([38, 62]) # random
|
| not like:
|
| >>> np.random.multinomial(100, [1.0, 2.0]) # WRONG
| Traceback (most recent call last):
| ValueError: pvals < 0, pvals > 1 or pvals contains NaNs
|
| multivariate_normal(self, mean, cov, size=None, check_valid='warn', tol=1e-08)
| multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8)
|
| Draw random samples from a multivariate normal distribution.
|
| The multivariate normal, multinormal or Gaussian distribution is a
| generalization of the one-dimensional normal distribution to higher
| dimensions. Such a distribution is specified by its mean and
| covariance matrix. These parameters are analogous to the mean
| (average or "center") and variance (standard deviation, or "width,"
| squared) of the one-dimensional normal distribution.
|
| .. note::
| New code should use the
| `~numpy.random.Generator.multivariate_normal`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| mean : 1-D array_like, of length N
| Mean of the N-dimensional distribution.
| cov : 2-D array_like, of shape (N, N)
| Covariance matrix of the distribution. It must be symmetric and
| positive-semidefinite for proper sampling.
| size : int or tuple of ints, optional
| Given a shape of, for example, ``(m,n,k)``, ``m*n*k`` samples are
| generated, and packed in an `m`-by-`n`-by-`k` arrangement. Because
| each sample is `N`-dimensional, the output shape is ``(m,n,k,N)``.
| If no shape is specified, a single (`N`-D) sample is returned.
| check_valid : { 'warn', 'raise', 'ignore' }, optional
| Behavior when the covariance matrix is not positive semidefinite.
| tol : float, optional
| Tolerance when checking the singular values in covariance matrix.
| cov is cast to double before the check.
|
| Returns
| -------
| out : ndarray
| The drawn samples, of shape *size*, if that was provided. If not,
| the shape is ``(N,)``.
|
| In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
| value drawn from the distribution.
|
| See Also
| --------
| random.Generator.multivariate_normal: which should be used for new code.
|
| Notes
| -----
| The mean is a coordinate in N-dimensional space, which represents the
| location where samples are most likely to be generated. This is
| analogous to the peak of the bell curve for the one-dimensional or
| univariate normal distribution.
|
| Covariance indicates the level to which two variables vary together.
| From the multivariate normal distribution, we draw N-dimensional
| samples, :math:`X = [x_1, x_2, ... x_N]`. The covariance matrix
| element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`.
| The element :math:`C_{ii}` is the variance of :math:`x_i` (i.e. its
| "spread").
|
| Instead of specifying the full covariance matrix, popular
| approximations include:
|
| - Spherical covariance (`cov` is a multiple of the identity matrix)
| - Diagonal covariance (`cov` has non-negative elements, and only on
| the diagonal)
|
| This geometrical property can be seen in two dimensions by plotting
| generated data-points:
|
| >>> mean = [0, 0]
| >>> cov = [[1, 0], [0, 100]] # diagonal covariance
|
| Diagonal covariance means that points are oriented along x or y-axis:
|
| >>> import matplotlib.pyplot as plt
| >>> x, y = np.random.multivariate_normal(mean, cov, 5000).T
| >>> plt.plot(x, y, 'x')
| >>> plt.axis('equal')
| >>> plt.show()
|
| Note that the covariance matrix must be positive semidefinite (a.k.a.
| nonnegative-definite). Otherwise, the behavior of this method is
| undefined and backwards compatibility is not guaranteed.
|
| References
| ----------
| .. [1] Papoulis, A., "Probability, Random Variables, and Stochastic
| Processes," 3rd ed., New York: McGraw-Hill, 1991.
| .. [2] Duda, R. O., Hart, P. E., and Stork, D. G., "Pattern
| Classification," 2nd ed., New York: Wiley, 2001.
|
| Examples
| --------
| >>> mean = (1, 2)
| >>> cov = [[1, 0], [0, 1]]
| >>> x = np.random.multivariate_normal(mean, cov, (3, 3))
| >>> x.shape
| (3, 3, 2)
|
| Here we generate 800 samples from the bivariate normal distribution
| with mean [0, 0] and covariance matrix [[6, -3], [-3, 3.5]]. The
| expected variances of the first and second components of the sample
| are 6 and 3.5, respectively, and the expected correlation
| coefficient is -3/sqrt(6*3.5) ≈ -0.65465.
|
| >>> cov = np.array([[6, -3], [-3, 3.5]])
| >>> pts = np.random.multivariate_normal([0, 0], cov, size=800)
|
| Check that the mean, covariance, and correlation coefficient of the
| sample are close to the expected values:
|
| >>> pts.mean(axis=0)
| array([ 0.0326911 , -0.01280782]) # may vary
| >>> np.cov(pts.T)
| array([[ 5.96202397, -2.85602287],
| [-2.85602287, 3.47613949]]) # may vary
| >>> np.corrcoef(pts.T)[0, 1]
| -0.6273591314603949 # may vary
|
| We can visualize this data with a scatter plot. The orientation
| of the point cloud illustrates the negative correlation of the
| components of this sample.
|
| >>> import matplotlib.pyplot as plt
| >>> plt.plot(pts[:, 0], pts[:, 1], '.', alpha=0.5)
| >>> plt.axis('equal')
| >>> plt.grid()
| >>> plt.show()
|
| negative_binomial(self, n, p, size=None)
| negative_binomial(n, p, size=None)
|
| Draw samples from a negative binomial distribution.
|
| Samples are drawn from a negative binomial distribution with specified
| parameters, `n` successes and `p` probability of success where `n`
| is > 0 and `p` is in the interval [0, 1].
|
| .. note::
| New code should use the
| `~numpy.random.Generator.negative_binomial`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| n : float or array_like of floats
| Parameter of the distribution, > 0.
| p : float or array_like of floats
| Parameter of the distribution, >= 0 and <=1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``n`` and ``p`` are both scalars.
| Otherwise, ``np.broadcast(n, p).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized negative binomial distribution,
| where each sample is equal to N, the number of failures that
| occurred before a total of n successes was reached.
|
| .. warning::
| This function returns the C-long dtype, which is 32bit on windows
| and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones).
| Since NumPy 2.0, NumPy's default integer is 32bit on 32bit platforms
| and 64bit on 64bit platforms.
|
| See Also
| --------
| random.Generator.negative_binomial: which should be used for new code.
|
| Notes
| -----
| The probability mass function of the negative binomial distribution is
|
| .. math:: P(N;n,p) = \frac{\Gamma(N+n)}{N!\Gamma(n)}p^{n}(1-p)^{N},
|
| where :math:`n` is the number of successes, :math:`p` is the
| probability of success, :math:`N+n` is the number of trials, and
| :math:`\Gamma` is the gamma function. When :math:`n` is an integer,
| :math:`\frac{\Gamma(N+n)}{N!\Gamma(n)} = \binom{N+n-1}{N}`, which is
| the more common form of this term in the pmf. The negative
| binomial distribution gives the probability of N failures given n
| successes, with a success on the last trial.
|
| If one throws a die repeatedly until the third time a "1" appears,
| then the probability distribution of the number of non-"1"s that
| appear before the third "1" is a negative binomial distribution.
|
| References
| ----------
| .. [1] Weisstein, Eric W. "Negative Binomial Distribution." From
| MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/NegativeBinomialDistribution.html
| .. [2] Wikipedia, "Negative binomial distribution",
| https://en.wikipedia.org/wiki/Negative_binomial_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| A real world example. A company drills wild-cat oil
| exploration wells, each with an estimated probability of
| success of 0.1. What is the probability of having one success
| for each successive well, that is what is the probability of a
| single success after drilling 5 wells, after 6 wells, etc.?
|
| >>> s = np.random.negative_binomial(1, 0.1, 100000)
| >>> for i in range(1, 11): # doctest: +SKIP
| ... probability = sum(s<i) / 100000.
| ... print(i, "wells drilled, probability of one success =", probability)
|
| noncentral_chisquare(self, df, nonc, size=None)
| noncentral_chisquare(df, nonc, size=None)
|
| Draw samples from a noncentral chi-square distribution.
|
| The noncentral :math:`\chi^2` distribution is a generalization of
| the :math:`\chi^2` distribution.
|
| .. note::
| New code should use the
| `~numpy.random.Generator.noncentral_chisquare`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| df : float or array_like of floats
| Degrees of freedom, must be > 0.
|
| .. versionchanged:: 1.10.0
| Earlier NumPy versions required dfnum > 1.
| nonc : float or array_like of floats
| Non-centrality, must be non-negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``df`` and ``nonc`` are both scalars.
| Otherwise, ``np.broadcast(df, nonc).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized noncentral chi-square distribution.
|
| See Also
| --------
| random.Generator.noncentral_chisquare: which should be used for new code.
|
| Notes
| -----
| The probability density function for the noncentral Chi-square
| distribution is
|
| .. math:: P(x;df,nonc) = \sum^{\infty}_{i=0}
| \frac{e^{-nonc/2}(nonc/2)^{i}}{i!}
| P_{Y_{df+2i}}(x),
|
| where :math:`Y_{q}` is the Chi-square with q degrees of freedom.
|
| References
| ----------
| .. [1] Wikipedia, "Noncentral chi-squared distribution"
| https://en.wikipedia.org/wiki/Noncentral_chi-squared_distribution
|
| Examples
| --------
| Draw values from the distribution and plot the histogram
|
| >>> import matplotlib.pyplot as plt
| >>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),
| ... bins=200, density=True)
| >>> plt.show()
|
| Draw values from a noncentral chisquare with very small noncentrality,
| and compare to a chisquare.
|
| >>> plt.figure()
| >>> values = plt.hist(np.random.noncentral_chisquare(3, .0000001, 100000),
| ... bins=np.arange(0., 25, .1), density=True)
| >>> values2 = plt.hist(np.random.chisquare(3, 100000),
| ... bins=np.arange(0., 25, .1), density=True)
| >>> plt.plot(values[1][0:-1], values[0]-values2[0], 'ob')
| >>> plt.show()
|
| Demonstrate how large values of non-centrality lead to a more symmetric
| distribution.
|
| >>> plt.figure()
| >>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),
| ... bins=200, density=True)
| >>> plt.show()
|
| noncentral_f(self, dfnum, dfden, nonc, size=None)
| noncentral_f(dfnum, dfden, nonc, size=None)
|
| Draw samples from the noncentral F distribution.
|
| Samples are drawn from an F distribution with specified parameters,
| `dfnum` (degrees of freedom in numerator) and `dfden` (degrees of
| freedom in denominator), where both parameters > 1.
| `nonc` is the non-centrality parameter.
|
| .. note::
| New code should use the
| `~numpy.random.Generator.noncentral_f`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| dfnum : float or array_like of floats
| Numerator degrees of freedom, must be > 0.
|
| .. versionchanged:: 1.14.0
| Earlier NumPy versions required dfnum > 1.
| dfden : float or array_like of floats
| Denominator degrees of freedom, must be > 0.
| nonc : float or array_like of floats
| Non-centrality parameter, the sum of the squares of the numerator
| means, must be >= 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``dfnum``, ``dfden``, and ``nonc``
| are all scalars. Otherwise, ``np.broadcast(dfnum, dfden, nonc).size``
| samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized noncentral Fisher distribution.
|
| See Also
| --------
| random.Generator.noncentral_f: which should be used for new code.
|
| Notes
| -----
| When calculating the power of an experiment (power = probability of
| rejecting the null hypothesis when a specific alternative is true) the
| non-central F statistic becomes important. When the null hypothesis is
| true, the F statistic follows a central F distribution. When the null
| hypothesis is not true, then it follows a non-central F statistic.
|
| References
| ----------
| .. [1] Weisstein, Eric W. "Noncentral F-Distribution."
| From MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/NoncentralF-Distribution.html
| .. [2] Wikipedia, "Noncentral F-distribution",
| https://en.wikipedia.org/wiki/Noncentral_F-distribution
|
| Examples
| --------
| In a study, testing for a specific alternative to the null hypothesis
| requires use of the Noncentral F distribution. We need to calculate the
| area in the tail of the distribution that exceeds the value of the F
| distribution for the null hypothesis. We'll plot the two probability
| distributions for comparison.
|
| >>> dfnum = 3 # between group deg of freedom
| >>> dfden = 20 # within groups degrees of freedom
| >>> nonc = 3.0
| >>> nc_vals = np.random.noncentral_f(dfnum, dfden, nonc, 1000000)
| >>> NF = np.histogram(nc_vals, bins=50, density=True)
| >>> c_vals = np.random.f(dfnum, dfden, 1000000)
| >>> F = np.histogram(c_vals, bins=50, density=True)
| >>> import matplotlib.pyplot as plt
| >>> plt.plot(F[1][1:], F[0])
| >>> plt.plot(NF[1][1:], NF[0])
| >>> plt.show()
|
| normal(self, loc=0.0, scale=1.0, size=None)
| normal(loc=0.0, scale=1.0, size=None)
|
| Draw random samples from a normal (Gaussian) distribution.
|
| The probability density function of the normal distribution, first
| derived by De Moivre and 200 years later by both Gauss and Laplace
| independently [2]_, is often called the bell curve because of
| its characteristic shape (see the example below).
|
| The normal distributions occurs often in nature. For example, it
| describes the commonly occurring distribution of samples influenced
| by a large number of tiny, random disturbances, each with its own
| unique distribution [2]_.
|
| .. note::
| New code should use the `~numpy.random.Generator.normal`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| loc : float or array_like of floats
| Mean ("centre") of the distribution.
| scale : float or array_like of floats
| Standard deviation (spread or "width") of the distribution. Must be
| non-negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``loc`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized normal distribution.
|
| See Also
| --------
| scipy.stats.norm : probability density function, distribution or
| cumulative density function, etc.
| random.Generator.normal: which should be used for new code.
|
| Notes
| -----
| The probability density for the Gaussian distribution is
|
| .. math:: p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }}
| e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },
|
| where :math:`\mu` is the mean and :math:`\sigma` the standard
| deviation. The square of the standard deviation, :math:`\sigma^2`,
| is called the variance.
|
| The function has its peak at the mean, and its "spread" increases with
| the standard deviation (the function reaches 0.607 times its maximum at
| :math:`x + \sigma` and :math:`x - \sigma` [2]_). This implies that
| normal is more likely to return samples lying close to the mean, rather
| than those far away.
|
| References
| ----------
| .. [1] Wikipedia, "Normal distribution",
| https://en.wikipedia.org/wiki/Normal_distribution
| .. [2] P. R. Peebles Jr., "Central Limit Theorem" in "Probability,
| Random Variables and Random Signal Principles", 4th ed., 2001,
| pp. 51, 51, 125.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> mu, sigma = 0, 0.1 # mean and standard deviation
| >>> s = np.random.normal(mu, sigma, 1000)
|
| Verify the mean and the variance:
|
| >>> abs(mu - np.mean(s))
| 0.0 # may vary
|
| >>> abs(sigma - np.std(s, ddof=1))
| 0.1 # may vary
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, ignored = plt.hist(s, 30, density=True)
| >>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
| ... np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
| ... linewidth=2, color='r')
| >>> plt.show()
|
| Two-by-four array of samples from the normal distribution with
| mean 3 and standard deviation 2.5:
|
| >>> np.random.normal(3, 2.5, size=(2, 4))
| array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random
| [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random
|
| pareto(self, a, size=None)
| pareto(a, size=None)
|
| Draw samples from a Pareto II or Lomax distribution with
| specified shape.
|
| The Lomax or Pareto II distribution is a shifted Pareto
| distribution. The classical Pareto distribution can be
| obtained from the Lomax distribution by adding 1 and
| multiplying by the scale parameter ``m`` (see Notes). The
| smallest value of the Lomax distribution is zero while for the
| classical Pareto distribution it is ``mu``, where the standard
| Pareto distribution has location ``mu = 1``. Lomax can also
| be considered as a simplified version of the Generalized
| Pareto distribution (available in SciPy), with the scale set
| to one and the location set to zero.
|
| The Pareto distribution must be greater than zero, and is
| unbounded above. It is also known as the "80-20 rule". In
| this distribution, 80 percent of the weights are in the lowest
| 20 percent of the range, while the other 20 percent fill the
| remaining 80 percent of the range.
|
| .. note::
| New code should use the `~numpy.random.Generator.pareto`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| a : float or array_like of floats
| Shape of the distribution. Must be positive.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``a`` is a scalar. Otherwise,
| ``np.array(a).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Pareto distribution.
|
| See Also
| --------
| scipy.stats.lomax : probability density function, distribution or
| cumulative density function, etc.
| scipy.stats.genpareto : probability density function, distribution or
| cumulative density function, etc.
| random.Generator.pareto: which should be used for new code.
|
| Notes
| -----
| The probability density for the Pareto distribution is
|
| .. math:: p(x) = \frac{am^a}{x^{a+1}}
|
| where :math:`a` is the shape and :math:`m` the scale.
|
| The Pareto distribution, named after the Italian economist
| Vilfredo Pareto, is a power law probability distribution
| useful in many real world problems. Outside the field of
| economics it is generally referred to as the Bradford
| distribution. Pareto developed the distribution to describe
| the distribution of wealth in an economy. It has also found
| use in insurance, web page access statistics, oil field sizes,
| and many other problems, including the download frequency for
| projects in Sourceforge [1]_. It is one of the so-called
| "fat-tailed" distributions.
|
| References
| ----------
| .. [1] Francis Hunt and Paul Johnson, On the Pareto Distribution of
| Sourceforge projects.
| .. [2] Pareto, V. (1896). Course of Political Economy. Lausanne.
| .. [3] Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme
| Values, Birkhauser Verlag, Basel, pp 23-30.
| .. [4] Wikipedia, "Pareto distribution",
| https://en.wikipedia.org/wiki/Pareto_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> a, m = 3., 2. # shape and mode
| >>> s = (np.random.pareto(a, 1000) + 1) * m
|
| Display the histogram of the samples, along with the probability
| density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, _ = plt.hist(s, 100, density=True)
| >>> fit = a*m**a / bins**(a+1)
| >>> plt.plot(bins, max(count)*fit/max(fit), linewidth=2, color='r')
| >>> plt.show()
|
| permutation(self, x)
| permutation(x)
|
| Randomly permute a sequence, or return a permuted range.
|
| If `x` is a multi-dimensional array, it is only shuffled along its
| first index.
|
| .. note::
| New code should use the
| `~numpy.random.Generator.permutation`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| x : int or array_like
| If `x` is an integer, randomly permute ``np.arange(x)``.
| If `x` is an array, make a copy and shuffle the elements
| randomly.
|
| Returns
| -------
| out : ndarray
| Permuted sequence or array range.
|
| See Also
| --------
| random.Generator.permutation: which should be used for new code.
|
| Examples
| --------
| >>> np.random.permutation(10)
| array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6]) # random
|
| >>> np.random.permutation([1, 4, 9, 12, 15])
| array([15, 1, 9, 4, 12]) # random
|
| >>> arr = np.arange(9).reshape((3, 3))
| >>> np.random.permutation(arr)
| array([[6, 7, 8], # random
| [0, 1, 2],
| [3, 4, 5]])
|
| poisson(self, lam=1.0, size=None)
| poisson(lam=1.0, size=None)
|
| Draw samples from a Poisson distribution.
|
| The Poisson distribution is the limit of the binomial distribution
| for large N.
|
| .. note::
| New code should use the `~numpy.random.Generator.poisson`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| lam : float or array_like of floats
| Expected number of events occurring in a fixed-time interval,
| must be >= 0. A sequence must be broadcastable over the requested
| size.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``lam`` is a scalar. Otherwise,
| ``np.array(lam).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Poisson distribution.
|
| See Also
| --------
| random.Generator.poisson: which should be used for new code.
|
| Notes
| -----
| The Poisson distribution
|
| .. math:: f(k; \lambda)=\frac{\lambda^k e^{-\lambda}}{k!}
|
| For events with an expected separation :math:`\lambda` the Poisson
| distribution :math:`f(k; \lambda)` describes the probability of
| :math:`k` events occurring within the observed
| interval :math:`\lambda`.
|
| Because the output is limited to the range of the C int64 type, a
| ValueError is raised when `lam` is within 10 sigma of the maximum
| representable value.
|
| References
| ----------
| .. [1] Weisstein, Eric W. "Poisson Distribution."
| From MathWorld--A Wolfram Web Resource.
| https://mathworld.wolfram.com/PoissonDistribution.html
| .. [2] Wikipedia, "Poisson distribution",
| https://en.wikipedia.org/wiki/Poisson_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> import numpy as np
| >>> s = np.random.poisson(5, 10000)
|
| Display histogram of the sample:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, ignored = plt.hist(s, 14, density=True)
| >>> plt.show()
|
| Draw each 100 values for lambda 100 and 500:
|
| >>> s = np.random.poisson(lam=(100., 500.), size=(100, 2))
|
| power(self, a, size=None)
| power(a, size=None)
|
| Draws samples in [0, 1] from a power distribution with positive
| exponent a - 1.
|
| Also known as the power function distribution.
|
| .. note::
| New code should use the `~numpy.random.Generator.power`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| a : float or array_like of floats
| Parameter of the distribution. Must be non-negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``a`` is a scalar. Otherwise,
| ``np.array(a).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized power distribution.
|
| Raises
| ------
| ValueError
| If a <= 0.
|
| See Also
| --------
| random.Generator.power: which should be used for new code.
|
| Notes
| -----
| The probability density function is
|
| .. math:: P(x; a) = ax^{a-1}, 0 \le x \le 1, a>0.
|
| The power function distribution is just the inverse of the Pareto
| distribution. It may also be seen as a special case of the Beta
| distribution.
|
| It is used, for example, in modeling the over-reporting of insurance
| claims.
|
| References
| ----------
| .. [1] Christian Kleiber, Samuel Kotz, "Statistical size distributions
| in economics and actuarial sciences", Wiley, 2003.
| .. [2] Heckert, N. A. and Filliben, James J. "NIST Handbook 148:
| Dataplot Reference Manual, Volume 2: Let Subcommands and Library
| Functions", National Institute of Standards and Technology
| Handbook Series, June 2003.
| https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/powpdf.pdf
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> a = 5. # shape
| >>> samples = 1000
| >>> s = np.random.power(a, samples)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, ignored = plt.hist(s, bins=30)
| >>> x = np.linspace(0, 1, 100)
| >>> y = a*x**(a-1.)
| >>> normed_y = samples*np.diff(bins)[0]*y
| >>> plt.plot(x, normed_y)
| >>> plt.show()
|
| Compare the power function distribution to the inverse of the Pareto.
|
| >>> from scipy import stats # doctest: +SKIP
| >>> rvs = np.random.power(5, 1000000)
| >>> rvsp = np.random.pareto(5, 1000000)
| >>> xx = np.linspace(0,1,100)
| >>> powpdf = stats.powerlaw.pdf(xx,5) # doctest: +SKIP
|
| >>> plt.figure()
| >>> plt.hist(rvs, bins=50, density=True)
| >>> plt.plot(xx,powpdf,'r-') # doctest: +SKIP
| >>> plt.title('np.random.power(5)')
|
| >>> plt.figure()
| >>> plt.hist(1./(1.+rvsp), bins=50, density=True)
| >>> plt.plot(xx,powpdf,'r-') # doctest: +SKIP
| >>> plt.title('inverse of 1 + np.random.pareto(5)')
|
| >>> plt.figure()
| >>> plt.hist(1./(1.+rvsp), bins=50, density=True)
| >>> plt.plot(xx,powpdf,'r-') # doctest: +SKIP
| >>> plt.title('inverse of stats.pareto(5)')
|
| rand(self, *args)
| rand(d0, d1, ..., dn)
|
| Random values in a given shape.
|
| .. note::
| This is a convenience function for users porting code from Matlab,
| and wraps `random_sample`. That function takes a
| tuple to specify the size of the output, which is consistent with
| other NumPy functions like `numpy.zeros` and `numpy.ones`.
|
| Create an array of the given shape and populate it with
| random samples from a uniform distribution
| over ``[0, 1)``.
|
| Parameters
| ----------
| d0, d1, ..., dn : int, optional
| The dimensions of the returned array, must be non-negative.
| If no argument is given a single Python float is returned.
|
| Returns
| -------
| out : ndarray, shape ``(d0, d1, ..., dn)``
| Random values.
|
| See Also
| --------
| random
|
| Examples
| --------
| >>> np.random.rand(3,2)
| array([[ 0.14022471, 0.96360618], #random
| [ 0.37601032, 0.25528411], #random
| [ 0.49313049, 0.94909878]]) #random
|
| randint(self, low, high=None, size=None, dtype=<class 'int'>)
| randint(low, high=None, size=None, dtype=int)
|
| Return random integers from `low` (inclusive) to `high` (exclusive).
|
| Return random integers from the "discrete uniform" distribution of
| the specified dtype in the "half-open" interval [`low`, `high`). If
| `high` is None (the default), then results are from [0, `low`).
|
| .. note::
| New code should use the `~numpy.random.Generator.integers`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| low : int or array-like of ints
| Lowest (signed) integers to be drawn from the distribution (unless
| ``high=None``, in which case this parameter is one above the
| *highest* such integer).
| high : int or array-like of ints, optional
| If provided, one above the largest (signed) integer to be drawn
| from the distribution (see above for behavior if ``high=None``).
| If array-like, must contain integer values
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| dtype : dtype, optional
| Desired dtype of the result. Byteorder must be native.
| The default value is long.
|
| .. versionadded:: 1.11.0
|
| .. warning::
| This function defaults to the C-long dtype, which is 32bit on windows
| and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones).
| Since NumPy 2.0, NumPy's default integer is 32bit on 32bit platforms
| and 64bit on 64bit platforms. Which corresponds to `np.intp`.
| (`dtype=int` is not the same as in most NumPy functions.)
|
| Returns
| -------
| out : int or ndarray of ints
| `size`-shaped array of random integers from the appropriate
| distribution, or a single such random int if `size` not provided.
|
| See Also
| --------
| random_integers : similar to `randint`, only for the closed
| interval [`low`, `high`], and 1 is the lowest value if `high` is
| omitted.
| random.Generator.integers: which should be used for new code.
|
| Examples
| --------
| >>> np.random.randint(2, size=10)
| array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) # random
| >>> np.random.randint(1, size=10)
| array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
|
| Generate a 2 x 4 array of ints between 0 and 4, inclusive:
|
| >>> np.random.randint(5, size=(2, 4))
| array([[4, 0, 2, 1], # random
| [3, 2, 2, 0]])
|
| Generate a 1 x 3 array with 3 different upper bounds
|
| >>> np.random.randint(1, [3, 5, 10])
| array([2, 2, 9]) # random
|
| Generate a 1 by 3 array with 3 different lower bounds
|
| >>> np.random.randint([1, 5, 7], 10)
| array([9, 8, 7]) # random
|
| Generate a 2 by 4 array using broadcasting with dtype of uint8
|
| >>> np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
| array([[ 8, 6, 9, 7], # random
| [ 1, 16, 9, 12]], dtype=uint8)
|
| randn(self, *args)
| randn(d0, d1, ..., dn)
|
| Return a sample (or samples) from the "standard normal" distribution.
|
| .. note::
| This is a convenience function for users porting code from Matlab,
| and wraps `standard_normal`. That function takes a
| tuple to specify the size of the output, which is consistent with
| other NumPy functions like `numpy.zeros` and `numpy.ones`.
|
| .. note::
| New code should use the
| `~numpy.random.Generator.standard_normal`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| If positive int_like arguments are provided, `randn` generates an array
| of shape ``(d0, d1, ..., dn)``, filled
| with random floats sampled from a univariate "normal" (Gaussian)
| distribution of mean 0 and variance 1. A single float randomly sampled
| from the distribution is returned if no argument is provided.
|
| Parameters
| ----------
| d0, d1, ..., dn : int, optional
| The dimensions of the returned array, must be non-negative.
| If no argument is given a single Python float is returned.
|
| Returns
| -------
| Z : ndarray or float
| A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from
| the standard normal distribution, or a single such float if
| no parameters were supplied.
|
| See Also
| --------
| standard_normal : Similar, but takes a tuple as its argument.
| normal : Also accepts mu and sigma arguments.
| random.Generator.standard_normal: which should be used for new code.
|
| Notes
| -----
| For random samples from the normal distribution with mean ``mu`` and
| standard deviation ``sigma``, use::
|
| sigma * np.random.randn(...) + mu
|
| Examples
| --------
| >>> np.random.randn()
| 2.1923875335537315 # random
|
| Two-by-four array of samples from the normal distribution with
| mean 3 and standard deviation 2.5:
|
| >>> 3 + 2.5 * np.random.randn(2, 4)
| array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random
| [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random
|
| random(self, size=None)
| random(size=None)
|
| Return random floats in the half-open interval [0.0, 1.0). Alias for
| `random_sample` to ease forward-porting to the new random API.
|
| random_integers(self, low, high=None, size=None)
| random_integers(low, high=None, size=None)
|
| Random integers of type `numpy.int_` between `low` and `high`, inclusive.
|
| Return random integers of type `numpy.int_` from the "discrete uniform"
| distribution in the closed interval [`low`, `high`]. If `high` is
| None (the default), then results are from [1, `low`]. The `numpy.int_`
| type translates to the C long integer type and its precision
| is platform dependent.
|
| This function has been deprecated. Use randint instead.
|
| .. deprecated:: 1.11.0
|
| Parameters
| ----------
| low : int
| Lowest (signed) integer to be drawn from the distribution (unless
| ``high=None``, in which case this parameter is the *highest* such
| integer).
| high : int, optional
| If provided, the largest (signed) integer to be drawn from the
| distribution (see above for behavior if ``high=None``).
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
|
| Returns
| -------
| out : int or ndarray of ints
| `size`-shaped array of random integers from the appropriate
| distribution, or a single such random int if `size` not provided.
|
| See Also
| --------
| randint : Similar to `random_integers`, only for the half-open
| interval [`low`, `high`), and 0 is the lowest value if `high` is
| omitted.
|
| Notes
| -----
| To sample from N evenly spaced floating-point numbers between a and b,
| use::
|
| a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.)
|
| Examples
| --------
| >>> np.random.random_integers(5)
| 4 # random
| >>> type(np.random.random_integers(5))
| <class 'numpy.int64'>
| >>> np.random.random_integers(5, size=(3,2))
| array([[5, 4], # random
| [3, 3],
| [4, 5]])
|
| Choose five random numbers from the set of five evenly-spaced
| numbers between 0 and 2.5, inclusive (*i.e.*, from the set
| :math:`{0, 5/8, 10/8, 15/8, 20/8}`):
|
| >>> 2.5 * (np.random.random_integers(5, size=(5,)) - 1) / 4.
| array([ 0.625, 1.25 , 0.625, 0.625, 2.5 ]) # random
|
| Roll two six sided dice 1000 times and sum the results:
|
| >>> d1 = np.random.random_integers(1, 6, 1000)
| >>> d2 = np.random.random_integers(1, 6, 1000)
| >>> dsums = d1 + d2
|
| Display results as a histogram:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, ignored = plt.hist(dsums, 11, density=True)
| >>> plt.show()
|
| random_sample(self, size=None)
| random_sample(size=None)
|
| Return random floats in the half-open interval [0.0, 1.0).
|
| Results are from the "continuous uniform" distribution over the
| stated interval. To sample :math:`Unif[a, b), b > a` multiply
| the output of `random_sample` by `(b-a)` and add `a`::
|
| (b - a) * random_sample() + a
|
| .. note::
| New code should use the `~numpy.random.Generator.random`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
|
| Returns
| -------
| out : float or ndarray of floats
| Array of random floats of shape `size` (unless ``size=None``, in which
| case a single float is returned).
|
| See Also
| --------
| random.Generator.random: which should be used for new code.
|
| Examples
| --------
| >>> np.random.random_sample()
| 0.47108547995356098 # random
| >>> type(np.random.random_sample())
| <class 'float'>
| >>> np.random.random_sample((5,))
| array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428]) # random
|
| Three-by-two array of random numbers from [-5, 0):
|
| >>> 5 * np.random.random_sample((3, 2)) - 5
| array([[-3.99149989, -0.52338984], # random
| [-2.99091858, -0.79479508],
| [-1.23204345, -1.75224494]])
|
| rayleigh(self, scale=1.0, size=None)
| rayleigh(scale=1.0, size=None)
|
| Draw samples from a Rayleigh distribution.
|
| The :math:`\chi` and Weibull distributions are generalizations of the
| Rayleigh.
|
| .. note::
| New code should use the `~numpy.random.Generator.rayleigh`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| scale : float or array_like of floats, optional
| Scale, also equals the mode. Must be non-negative. Default is 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``scale`` is a scalar. Otherwise,
| ``np.array(scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Rayleigh distribution.
|
| See Also
| --------
| random.Generator.rayleigh: which should be used for new code.
|
| Notes
| -----
| The probability density function for the Rayleigh distribution is
|
| .. math:: P(x;scale) = \frac{x}{scale^2}e^{\frac{-x^2}{2 \cdotp scale^2}}
|
| The Rayleigh distribution would arise, for example, if the East
| and North components of the wind velocity had identical zero-mean
| Gaussian distributions. Then the wind speed would have a Rayleigh
| distribution.
|
| References
| ----------
| .. [1] Brighton Webs Ltd., "Rayleigh Distribution,"
| https://web.archive.org/web/20090514091424/http://brighton-webs.co.uk:80/distributions/rayleigh.asp
| .. [2] Wikipedia, "Rayleigh distribution"
| https://en.wikipedia.org/wiki/Rayleigh_distribution
|
| Examples
| --------
| Draw values from the distribution and plot the histogram
|
| >>> from matplotlib.pyplot import hist
| >>> values = hist(np.random.rayleigh(3, 100000), bins=200, density=True)
|
| Wave heights tend to follow a Rayleigh distribution. If the mean wave
| height is 1 meter, what fraction of waves are likely to be larger than 3
| meters?
|
| >>> meanvalue = 1
| >>> modevalue = np.sqrt(2 / np.pi) * meanvalue
| >>> s = np.random.rayleigh(modevalue, 1000000)
|
| The percentage of waves larger than 3 meters is:
|
| >>> 100.*sum(s>3)/1000000.
| 0.087300000000000003 # random
|
| seed(self, seed=None)
| seed(seed=None)
|
| Reseed a legacy MT19937 BitGenerator
|
| Notes
| -----
| This is a convenience, legacy function.
|
| The best practice is to **not** reseed a BitGenerator, rather to
| recreate a new one. This method is here for legacy reasons.
| This example demonstrates best practice.
|
| >>> from numpy.random import MT19937
| >>> from numpy.random import RandomState, SeedSequence
| >>> rs = RandomState(MT19937(SeedSequence(123456789)))
| # Later, you want to restart the stream
| >>> rs = RandomState(MT19937(SeedSequence(987654321)))
|
| set_state(self, state)
| set_state(state)
|
| Set the internal state of the generator from a tuple.
|
| For use if one has reason to manually (re-)set the internal state of
| the bit generator used by the RandomState instance. By default,
| RandomState uses the "Mersenne Twister"[1]_ pseudo-random number
| generating algorithm.
|
| Parameters
| ----------
| state : {tuple(str, ndarray of 624 uints, int, int, float), dict}
| The `state` tuple has the following items:
|
| 1. the string 'MT19937', specifying the Mersenne Twister algorithm.
| 2. a 1-D array of 624 unsigned integers ``keys``.
| 3. an integer ``pos``.
| 4. an integer ``has_gauss``.
| 5. a float ``cached_gaussian``.
|
| If state is a dictionary, it is directly set using the BitGenerators
| `state` property.
|
| Returns
| -------
| out : None
| Returns 'None' on success.
|
| See Also
| --------
| get_state
|
| Notes
| -----
| `set_state` and `get_state` are not needed to work with any of the
| random distributions in NumPy. If the internal state is manually altered,
| the user should know exactly what he/she is doing.
|
| For backwards compatibility, the form (str, array of 624 uints, int) is
| also accepted although it is missing some information about the cached
| Gaussian value: ``state = ('MT19937', keys, pos)``.
|
| References
| ----------
| .. [1] M. Matsumoto and T. Nishimura, "Mersenne Twister: A
| 623-dimensionally equidistributed uniform pseudorandom number
| generator," *ACM Trans. on Modeling and Computer Simulation*,
| Vol. 8, No. 1, pp. 3-30, Jan. 1998.
|
| shuffle(self, x)
| shuffle(x)
|
| Modify a sequence in-place by shuffling its contents.
|
| This function only shuffles the array along the first axis of a
| multi-dimensional array. The order of sub-arrays is changed but
| their contents remains the same.
|
| .. note::
| New code should use the `~numpy.random.Generator.shuffle`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| x : ndarray or MutableSequence
| The array, list or mutable sequence to be shuffled.
|
| Returns
| -------
| None
|
| See Also
| --------
| random.Generator.shuffle: which should be used for new code.
|
| Examples
| --------
| >>> arr = np.arange(10)
| >>> np.random.shuffle(arr)
| >>> arr
| [1 7 5 2 9 4 3 6 0 8] # random
|
| Multi-dimensional arrays are only shuffled along the first axis:
|
| >>> arr = np.arange(9).reshape((3, 3))
| >>> np.random.shuffle(arr)
| >>> arr
| array([[3, 4, 5], # random
| [6, 7, 8],
| [0, 1, 2]])
|
| standard_cauchy(self, size=None)
| standard_cauchy(size=None)
|
| Draw samples from a standard Cauchy distribution with mode = 0.
|
| Also known as the Lorentz distribution.
|
| .. note::
| New code should use the
| `~numpy.random.Generator.standard_cauchy`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
|
| Returns
| -------
| samples : ndarray or scalar
| The drawn samples.
|
| See Also
| --------
| random.Generator.standard_cauchy: which should be used for new code.
|
| Notes
| -----
| The probability density function for the full Cauchy distribution is
|
| .. math:: P(x; x_0, \gamma) = \frac{1}{\pi \gamma \bigl[ 1+
| (\frac{x-x_0}{\gamma})^2 \bigr] }
|
| and the Standard Cauchy distribution just sets :math:`x_0=0` and
| :math:`\gamma=1`
|
| The Cauchy distribution arises in the solution to the driven harmonic
| oscillator problem, and also describes spectral line broadening. It
| also describes the distribution of values at which a line tilted at
| a random angle will cut the x axis.
|
| When studying hypothesis tests that assume normality, seeing how the
| tests perform on data from a Cauchy distribution is a good indicator of
| their sensitivity to a heavy-tailed distribution, since the Cauchy looks
| very much like a Gaussian distribution, but with heavier tails.
|
| References
| ----------
| .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "Cauchy
| Distribution",
| https://www.itl.nist.gov/div898/handbook/eda/section3/eda3663.htm
| .. [2] Weisstein, Eric W. "Cauchy Distribution." From MathWorld--A
| Wolfram Web Resource.
| https://mathworld.wolfram.com/CauchyDistribution.html
| .. [3] Wikipedia, "Cauchy distribution"
| https://en.wikipedia.org/wiki/Cauchy_distribution
|
| Examples
| --------
| Draw samples and plot the distribution:
|
| >>> import matplotlib.pyplot as plt
| >>> s = np.random.standard_cauchy(1000000)
| >>> s = s[(s>-25) & (s<25)] # truncate distribution so it plots well
| >>> plt.hist(s, bins=100)
| >>> plt.show()
|
| standard_exponential(self, size=None)
| standard_exponential(size=None)
|
| Draw samples from the standard exponential distribution.
|
| `standard_exponential` is identical to the exponential distribution
| with a scale parameter of 1.
|
| .. note::
| New code should use the
| `~numpy.random.Generator.standard_exponential`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
|
| Returns
| -------
| out : float or ndarray
| Drawn samples.
|
| See Also
| --------
| random.Generator.standard_exponential: which should be used for new code.
|
| Examples
| --------
| Output a 3x8000 array:
|
| >>> n = np.random.standard_exponential((3, 8000))
|
| standard_gamma(self, shape, size=None)
| standard_gamma(shape, size=None)
|
| Draw samples from a standard Gamma distribution.
|
| Samples are drawn from a Gamma distribution with specified parameters,
| shape (sometimes designated "k") and scale=1.
|
| .. note::
| New code should use the
| `~numpy.random.Generator.standard_gamma`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| shape : float or array_like of floats
| Parameter, must be non-negative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``shape`` is a scalar. Otherwise,
| ``np.array(shape).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized standard gamma distribution.
|
| See Also
| --------
| scipy.stats.gamma : probability density function, distribution or
| cumulative density function, etc.
| random.Generator.standard_gamma: which should be used for new code.
|
| Notes
| -----
| The probability density for the Gamma distribution is
|
| .. math:: p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},
|
| where :math:`k` is the shape and :math:`\theta` the scale,
| and :math:`\Gamma` is the Gamma function.
|
| The Gamma distribution is often used to model the times to failure of
| electronic components, and arises naturally in processes for which the
| waiting times between Poisson distributed events are relevant.
|
| References
| ----------
| .. [1] Weisstein, Eric W. "Gamma Distribution." From MathWorld--A
| Wolfram Web Resource.
| https://mathworld.wolfram.com/GammaDistribution.html
| .. [2] Wikipedia, "Gamma distribution",
| https://en.wikipedia.org/wiki/Gamma_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> shape, scale = 2., 1. # mean and width
| >>> s = np.random.standard_gamma(shape, 1000000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> import scipy.special as sps # doctest: +SKIP
| >>> count, bins, ignored = plt.hist(s, 50, density=True)
| >>> y = bins**(shape-1) * ((np.exp(-bins/scale))/ # doctest: +SKIP
| ... (sps.gamma(shape) * scale**shape))
| >>> plt.plot(bins, y, linewidth=2, color='r') # doctest: +SKIP
| >>> plt.show()
|
| standard_normal(self, size=None)
| standard_normal(size=None)
|
| Draw samples from a standard Normal distribution (mean=0, stdev=1).
|
| .. note::
| New code should use the
| `~numpy.random.Generator.standard_normal`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
|
| Returns
| -------
| out : float or ndarray
| A floating-point array of shape ``size`` of drawn samples, or a
| single sample if ``size`` was not specified.
|
| See Also
| --------
| normal :
| Equivalent function with additional ``loc`` and ``scale`` arguments
| for setting the mean and standard deviation.
| random.Generator.standard_normal: which should be used for new code.
|
| Notes
| -----
| For random samples from the normal distribution with mean ``mu`` and
| standard deviation ``sigma``, use one of::
|
| mu + sigma * np.random.standard_normal(size=...)
| np.random.normal(mu, sigma, size=...)
|
| Examples
| --------
| >>> np.random.standard_normal()
| 2.1923875335537315 #random
|
| >>> s = np.random.standard_normal(8000)
| >>> s
| array([ 0.6888893 , 0.78096262, -0.89086505, ..., 0.49876311, # random
| -0.38672696, -0.4685006 ]) # random
| >>> s.shape
| (8000,)
| >>> s = np.random.standard_normal(size=(3, 4, 2))
| >>> s.shape
| (3, 4, 2)
|
| Two-by-four array of samples from the normal distribution with
| mean 3 and standard deviation 2.5:
|
| >>> 3 + 2.5 * np.random.standard_normal(size=(2, 4))
| array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random
| [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random
|
| standard_t(self, df, size=None)
| standard_t(df, size=None)
|
| Draw samples from a standard Student's t distribution with `df` degrees
| of freedom.
|
| A special case of the hyperbolic distribution. As `df` gets
| large, the result resembles that of the standard normal
| distribution (`standard_normal`).
|
| .. note::
| New code should use the `~numpy.random.Generator.standard_t`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| df : float or array_like of floats
| Degrees of freedom, must be > 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``df`` is a scalar. Otherwise,
| ``np.array(df).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized standard Student's t distribution.
|
| See Also
| --------
| random.Generator.standard_t: which should be used for new code.
|
| Notes
| -----
| The probability density function for the t distribution is
|
| .. math:: P(x, df) = \frac{\Gamma(\frac{df+1}{2})}{\sqrt{\pi df}
| \Gamma(\frac{df}{2})}\Bigl( 1+\frac{x^2}{df} \Bigr)^{-(df+1)/2}
|
| The t test is based on an assumption that the data come from a
| Normal distribution. The t test provides a way to test whether
| the sample mean (that is the mean calculated from the data) is
| a good estimate of the true mean.
|
| The derivation of the t-distribution was first published in
| 1908 by William Gosset while working for the Guinness Brewery
| in Dublin. Due to proprietary issues, he had to publish under
| a pseudonym, and so he used the name Student.
|
| References
| ----------
| .. [1] Dalgaard, Peter, "Introductory Statistics With R",
| Springer, 2002.
| .. [2] Wikipedia, "Student's t-distribution"
| https://en.wikipedia.org/wiki/Student's_t-distribution
|
| Examples
| --------
| From Dalgaard page 83 [1]_, suppose the daily energy intake for 11
| women in kilojoules (kJ) is:
|
| >>> intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515, \
| ... 7515, 8230, 8770])
|
| Does their energy intake deviate systematically from the recommended
| value of 7725 kJ? Our null hypothesis will be the absence of deviation,
| and the alternate hypothesis will be the presence of an effect that could be
| either positive or negative, hence making our test 2-tailed.
|
| Because we are estimating the mean and we have N=11 values in our sample,
| we have N-1=10 degrees of freedom. We set our significance level to 95% and
| compute the t statistic using the empirical mean and empirical standard
| deviation of our intake. We use a ddof of 1 to base the computation of our
| empirical standard deviation on an unbiased estimate of the variance (note:
| the final estimate is not unbiased due to the concave nature of the square
| root).
|
| >>> np.mean(intake)
| 6753.636363636364
| >>> intake.std(ddof=1)
| 1142.1232221373727
| >>> t = (np.mean(intake)-7725)/(intake.std(ddof=1)/np.sqrt(len(intake)))
| >>> t
| -2.8207540608310198
|
| We draw 1000000 samples from Student's t distribution with the adequate
| degrees of freedom.
|
| >>> import matplotlib.pyplot as plt
| >>> s = np.random.standard_t(10, size=1000000)
| >>> h = plt.hist(s, bins=100, density=True)
|
| Does our t statistic land in one of the two critical regions found at
| both tails of the distribution?
|
| >>> np.sum(np.abs(t) < np.abs(s)) / float(len(s))
| 0.018318 #random < 0.05, statistic is in critical region
|
| The probability value for this 2-tailed test is about 1.83%, which is
| lower than the 5% pre-determined significance threshold.
|
| Therefore, the probability of observing values as extreme as our intake
| conditionally on the null hypothesis being true is too low, and we reject
| the null hypothesis of no deviation.
|
| tomaxint(self, size=None)
| tomaxint(size=None)
|
| Return a sample of uniformly distributed random integers in the interval
| [0, ``np.iinfo("long").max``].
|
| .. warning::
| This function uses the C-long dtype, which is 32bit on windows
| and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones).
| Since NumPy 2.0, NumPy's default integer is 32bit on 32bit platforms
| and 64bit on 64bit platforms.
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
|
| Returns
| -------
| out : ndarray
| Drawn samples, with shape `size`.
|
| See Also
| --------
| randint : Uniform sampling over a given half-open interval of integers.
| random_integers : Uniform sampling over a given closed interval of
| integers.
|
| Examples
| --------
| >>> rs = np.random.RandomState() # need a RandomState object
| >>> rs.tomaxint((2,2,2))
| array([[[1170048599, 1600360186], # random
| [ 739731006, 1947757578]],
| [[1871712945, 752307660],
| [1601631370, 1479324245]]])
| >>> rs.tomaxint((2,2,2)) < np.iinfo(np.int_).max
| array([[[ True, True],
| [ True, True]],
| [[ True, True],
| [ True, True]]])
|
| triangular(self, left, mode, right, size=None)
| triangular(left, mode, right, size=None)
|
| Draw samples from the triangular distribution over the
| interval ``[left, right]``.
|
| The triangular distribution is a continuous probability
| distribution with lower limit left, peak at mode, and upper
| limit right. Unlike the other distributions, these parameters
| directly define the shape of the pdf.
|
| .. note::
| New code should use the `~numpy.random.Generator.triangular`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| left : float or array_like of floats
| Lower limit.
| mode : float or array_like of floats
| The value where the peak of the distribution occurs.
| The value must fulfill the condition ``left <= mode <= right``.
| right : float or array_like of floats
| Upper limit, must be larger than `left`.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``left``, ``mode``, and ``right``
| are all scalars. Otherwise, ``np.broadcast(left, mode, right).size``
| samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized triangular distribution.
|
| See Also
| --------
| random.Generator.triangular: which should be used for new code.
|
| Notes
| -----
| The probability density function for the triangular distribution is
|
| .. math:: P(x;l, m, r) = \begin{cases}
| \frac{2(x-l)}{(r-l)(m-l)}& \text{for $l \leq x \leq m$},\\
| \frac{2(r-x)}{(r-l)(r-m)}& \text{for $m \leq x \leq r$},\\
| 0& \text{otherwise}.
| \end{cases}
|
| The triangular distribution is often used in ill-defined
| problems where the underlying distribution is not known, but
| some knowledge of the limits and mode exists. Often it is used
| in simulations.
|
| References
| ----------
| .. [1] Wikipedia, "Triangular distribution"
| https://en.wikipedia.org/wiki/Triangular_distribution
|
| Examples
| --------
| Draw values from the distribution and plot the histogram:
|
| >>> import matplotlib.pyplot as plt
| >>> h = plt.hist(np.random.triangular(-3, 0, 8, 100000), bins=200,
| ... density=True)
| >>> plt.show()
|
| uniform(self, low=0.0, high=1.0, size=None)
| uniform(low=0.0, high=1.0, size=None)
|
| Draw samples from a uniform distribution.
|
| Samples are uniformly distributed over the half-open interval
| ``[low, high)`` (includes low, but excludes high). In other words,
| any value within the given interval is equally likely to be drawn
| by `uniform`.
|
| .. note::
| New code should use the `~numpy.random.Generator.uniform`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| low : float or array_like of floats, optional
| Lower boundary of the output interval. All values generated will be
| greater than or equal to low. The default value is 0.
| high : float or array_like of floats
| Upper boundary of the output interval. All values generated will be
| less than or equal to high. The high limit may be included in the
| returned array of floats due to floating-point rounding in the
| equation ``low + (high-low) * random_sample()``. The default value
| is 1.0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``low`` and ``high`` are both scalars.
| Otherwise, ``np.broadcast(low, high).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized uniform distribution.
|
| See Also
| --------
| randint : Discrete uniform distribution, yielding integers.
| random_integers : Discrete uniform distribution over the closed
| interval ``[low, high]``.
| random_sample : Floats uniformly distributed over ``[0, 1)``.
| random : Alias for `random_sample`.
| rand : Convenience function that accepts dimensions as input, e.g.,
| ``rand(2,2)`` would generate a 2-by-2 array of floats,
| uniformly distributed over ``[0, 1)``.
| random.Generator.uniform: which should be used for new code.
|
| Notes
| -----
| The probability density function of the uniform distribution is
|
| .. math:: p(x) = \frac{1}{b - a}
|
| anywhere within the interval ``[a, b)``, and zero elsewhere.
|
| When ``high`` == ``low``, values of ``low`` will be returned.
| If ``high`` < ``low``, the results are officially undefined
| and may eventually raise an error, i.e. do not rely on this
| function to behave when passed arguments satisfying that
| inequality condition. The ``high`` limit may be included in the
| returned array of floats due to floating-point rounding in the
| equation ``low + (high-low) * random_sample()``. For example:
|
| >>> x = np.float32(5*0.99999999)
| >>> x
| 5.0
|
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> s = np.random.uniform(-1,0,1000)
|
| All values are within the given interval:
|
| >>> np.all(s >= -1)
| True
| >>> np.all(s < 0)
| True
|
| Display the histogram of the samples, along with the
| probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> count, bins, ignored = plt.hist(s, 15, density=True)
| >>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
| >>> plt.show()
|
| vonmises(self, mu, kappa, size=None)
| vonmises(mu, kappa, size=None)
|
| Draw samples from a von Mises distribution.
|
| Samples are drawn from a von Mises distribution with specified mode
| (mu) and dispersion (kappa), on the interval [-pi, pi].
|
| The von Mises distribution (also known as the circular normal
| distribution) is a continuous probability distribution on the unit
| circle. It may be thought of as the circular analogue of the normal
| distribution.
|
| .. note::
| New code should use the `~numpy.random.Generator.vonmises`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| mu : float or array_like of floats
| Mode ("center") of the distribution.
| kappa : float or array_like of floats
| Dispersion of the distribution, has to be >=0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``mu`` and ``kappa`` are both scalars.
| Otherwise, ``np.broadcast(mu, kappa).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized von Mises distribution.
|
| See Also
| --------
| scipy.stats.vonmises : probability density function, distribution, or
| cumulative density function, etc.
| random.Generator.vonmises: which should be used for new code.
|
| Notes
| -----
| The probability density for the von Mises distribution is
|
| .. math:: p(x) = \frac{e^{\kappa cos(x-\mu)}}{2\pi I_0(\kappa)},
|
| where :math:`\mu` is the mode and :math:`\kappa` the dispersion,
| and :math:`I_0(\kappa)` is the modified Bessel function of order 0.
|
| The von Mises is named for Richard Edler von Mises, who was born in
| Austria-Hungary, in what is now the Ukraine. He fled to the United
| States in 1939 and became a professor at Harvard. He worked in
| probability theory, aerodynamics, fluid mechanics, and philosophy of
| science.
|
| References
| ----------
| .. [1] Abramowitz, M. and Stegun, I. A. (Eds.). "Handbook of
| Mathematical Functions with Formulas, Graphs, and Mathematical
| Tables, 9th printing," New York: Dover, 1972.
| .. [2] von Mises, R., "Mathematical Theory of Probability
| and Statistics", New York: Academic Press, 1964.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> mu, kappa = 0.0, 4.0 # mean and dispersion
| >>> s = np.random.vonmises(mu, kappa, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> from scipy.special import i0 # doctest: +SKIP
| >>> plt.hist(s, 50, density=True)
| >>> x = np.linspace(-np.pi, np.pi, num=51)
| >>> y = np.exp(kappa*np.cos(x-mu))/(2*np.pi*i0(kappa)) # doctest: +SKIP
| >>> plt.plot(x, y, linewidth=2, color='r') # doctest: +SKIP
| >>> plt.show()
|
| wald(self, mean, scale, size=None)
| wald(mean, scale, size=None)
|
| Draw samples from a Wald, or inverse Gaussian, distribution.
|
| As the scale approaches infinity, the distribution becomes more like a
| Gaussian. Some references claim that the Wald is an inverse Gaussian
| with mean equal to 1, but this is by no means universal.
|
| The inverse Gaussian distribution was first studied in relationship to
| Brownian motion. In 1956 M.C.K. Tweedie used the name inverse Gaussian
| because there is an inverse relationship between the time to cover a
| unit distance and distance covered in unit time.
|
| .. note::
| New code should use the `~numpy.random.Generator.wald`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| mean : float or array_like of floats
| Distribution mean, must be > 0.
| scale : float or array_like of floats
| Scale parameter, must be > 0.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``mean`` and ``scale`` are both scalars.
| Otherwise, ``np.broadcast(mean, scale).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Wald distribution.
|
| See Also
| --------
| random.Generator.wald: which should be used for new code.
|
| Notes
| -----
| The probability density function for the Wald distribution is
|
| .. math:: P(x;mean,scale) = \sqrt{\frac{scale}{2\pi x^3}}e^
| \frac{-scale(x-mean)^2}{2\cdotp mean^2x}
|
| As noted above the inverse Gaussian distribution first arise
| from attempts to model Brownian motion. It is also a
| competitor to the Weibull for use in reliability modeling and
| modeling stock returns and interest rate processes.
|
| References
| ----------
| .. [1] Brighton Webs Ltd., Wald Distribution,
| https://web.archive.org/web/20090423014010/http://www.brighton-webs.co.uk:80/distributions/wald.asp
| .. [2] Chhikara, Raj S., and Folks, J. Leroy, "The Inverse Gaussian
| Distribution: Theory : Methodology, and Applications", CRC Press,
| 1988.
| .. [3] Wikipedia, "Inverse Gaussian distribution"
| https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution
|
| Examples
| --------
| Draw values from the distribution and plot the histogram:
|
| >>> import matplotlib.pyplot as plt
| >>> h = plt.hist(np.random.wald(3, 2, 100000), bins=200, density=True)
| >>> plt.show()
|
| weibull(self, a, size=None)
| weibull(a, size=None)
|
| Draw samples from a Weibull distribution.
|
| Draw samples from a 1-parameter Weibull distribution with the given
| shape parameter `a`.
|
| .. math:: X = (-ln(U))^{1/a}
|
| Here, U is drawn from the uniform distribution over (0,1].
|
| The more common 2-parameter Weibull, including a scale parameter
| :math:`\lambda` is just :math:`X = \lambda(-ln(U))^{1/a}`.
|
| .. note::
| New code should use the `~numpy.random.Generator.weibull`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| a : float or array_like of floats
| Shape parameter of the distribution. Must be nonnegative.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``a`` is a scalar. Otherwise,
| ``np.array(a).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Weibull distribution.
|
| See Also
| --------
| scipy.stats.weibull_max
| scipy.stats.weibull_min
| scipy.stats.genextreme
| gumbel
| random.Generator.weibull: which should be used for new code.
|
| Notes
| -----
| The Weibull (or Type III asymptotic extreme value distribution
| for smallest values, SEV Type III, or Rosin-Rammler
| distribution) is one of a class of Generalized Extreme Value
| (GEV) distributions used in modeling extreme value problems.
| This class includes the Gumbel and Frechet distributions.
|
| The probability density for the Weibull distribution is
|
| .. math:: p(x) = \frac{a}
| {\lambda}(\frac{x}{\lambda})^{a-1}e^{-(x/\lambda)^a},
|
| where :math:`a` is the shape and :math:`\lambda` the scale.
|
| The function has its peak (the mode) at
| :math:`\lambda(\frac{a-1}{a})^{1/a}`.
|
| When ``a = 1``, the Weibull distribution reduces to the exponential
| distribution.
|
| References
| ----------
| .. [1] Waloddi Weibull, Royal Technical University, Stockholm,
| 1939 "A Statistical Theory Of The Strength Of Materials",
| Ingeniorsvetenskapsakademiens Handlingar Nr 151, 1939,
| Generalstabens Litografiska Anstalts Forlag, Stockholm.
| .. [2] Waloddi Weibull, "A Statistical Distribution Function of
| Wide Applicability", Journal Of Applied Mechanics ASME Paper
| 1951.
| .. [3] Wikipedia, "Weibull distribution",
| https://en.wikipedia.org/wiki/Weibull_distribution
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> a = 5. # shape
| >>> s = np.random.weibull(a, 1000)
|
| Display the histogram of the samples, along with
| the probability density function:
|
| >>> import matplotlib.pyplot as plt
| >>> x = np.arange(1,100.)/50.
| >>> def weib(x,n,a):
| ... return (a / n) * (x / n)**(a - 1) * np.exp(-(x / n)**a)
|
| >>> count, bins, ignored = plt.hist(np.random.weibull(5.,1000))
| >>> x = np.arange(1,100.)/50.
| >>> scale = count.max()/weib(x, 1., 5.).max()
| >>> plt.plot(x, weib(x, 1., 5.)*scale)
| >>> plt.show()
|
| zipf(self, a, size=None)
| zipf(a, size=None)
|
| Draw samples from a Zipf distribution.
|
| Samples are drawn from a Zipf distribution with specified parameter
| `a` > 1.
|
| The Zipf distribution (also known as the zeta distribution) is a
| discrete probability distribution that satisfies Zipf's law: the
| frequency of an item is inversely proportional to its rank in a
| frequency table.
|
| .. note::
| New code should use the `~numpy.random.Generator.zipf`
| method of a `~numpy.random.Generator` instance instead;
| please see the :ref:`random-quick-start`.
|
| Parameters
| ----------
| a : float or array_like of floats
| Distribution parameter. Must be greater than 1.
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. If size is ``None`` (default),
| a single value is returned if ``a`` is a scalar. Otherwise,
| ``np.array(a).size`` samples are drawn.
|
| Returns
| -------
| out : ndarray or scalar
| Drawn samples from the parameterized Zipf distribution.
|
| See Also
| --------
| scipy.stats.zipf : probability density function, distribution, or
| cumulative density function, etc.
| random.Generator.zipf: which should be used for new code.
|
| Notes
| -----
| The probability density for the Zipf distribution is
|
| .. math:: p(k) = \frac{k^{-a}}{\zeta(a)},
|
| for integers :math:`k \geq 1`, where :math:`\zeta` is the Riemann Zeta
| function.
|
| It is named for the American linguist George Kingsley Zipf, who noted
| that the frequency of any word in a sample of a language is inversely
| proportional to its rank in the frequency table.
|
| References
| ----------
| .. [1] Zipf, G. K., "Selected Studies of the Principle of Relative
| Frequency in Language," Cambridge, MA: Harvard Univ. Press,
| 1932.
|
| Examples
| --------
| Draw samples from the distribution:
|
| >>> a = 4.0
| >>> n = 20000
| >>> s = np.random.zipf(a, n)
|
| Display the histogram of the samples, along with
| the expected histogram based on the probability
| density function:
|
| >>> import matplotlib.pyplot as plt
| >>> from scipy.special import zeta # doctest: +SKIP
|
| `bincount` provides a fast histogram for small integers.
|
| >>> count = np.bincount(s)
| >>> k = np.arange(1, s.max() + 1)
|
| >>> plt.bar(k, count[1:], alpha=0.5, label='sample count')
| >>> plt.plot(k, n*(k**-a)/zeta(a), 'k.-', alpha=0.5,
| ... label='expected count') # doctest: +SKIP
| >>> plt.semilogy()
| >>> plt.grid(alpha=0.4)
| >>> plt.legend()
| >>> plt.title(f'Zipf sample, a={a}, size={n}')
| >>> plt.show()
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
class SFC64(numpy.random.bit_generator.BitGenerator)
| SFC64(seed=None)
|
| BitGenerator for Chris Doty-Humphrey's Small Fast Chaotic PRNG.
|
| Parameters
| ----------
| seed : {None, int, array_like[ints], SeedSequence}, optional
| A seed to initialize the `BitGenerator`. If None, then fresh,
| unpredictable entropy will be pulled from the OS. If an ``int`` or
| ``array_like[ints]`` is passed, then it will be passed to
| `SeedSequence` to derive the initial `BitGenerator` state. One may also
| pass in a `SeedSequence` instance.
|
| Notes
| -----
| `SFC64` is a 256-bit implementation of Chris Doty-Humphrey's Small Fast
| Chaotic PRNG ([1]_). `SFC64` has a few different cycles that one might be
| on, depending on the seed; the expected period will be about
| :math:`2^{255}` ([2]_). `SFC64` incorporates a 64-bit counter which means
| that the absolute minimum cycle length is :math:`2^{64}` and that distinct
| seeds will not run into each other for at least :math:`2^{64}` iterations.
|
| `SFC64` provides a capsule containing function pointers that produce
| doubles, and unsigned 32 and 64- bit integers. These are not
| directly consumable in Python and must be consumed by a `Generator`
| or similar object that supports low-level access.
|
| **State and Seeding**
|
| The `SFC64` state vector consists of 4 unsigned 64-bit values. The last
| is a 64-bit counter that increments by 1 each iteration.
|
| The input seed is processed by `SeedSequence` to generate the first
| 3 values, then the `SFC64` algorithm is iterated a small number of times
| to mix.
|
| **Compatibility Guarantee**
|
| `SFC64` makes a guarantee that a fixed seed will always produce the same
| random integer stream.
|
| References
| ----------
| .. [1] `"PractRand"
| <https://pracrand.sourceforge.net/RNG_engines.txt>`_
| .. [2] `"Random Invertible Mapping Statistics"
| <https://www.pcg-random.org/posts/random-invertible-mapping-statistics.html>`_
|
| Method resolution order:
| SFC64
| numpy.random.bit_generator.BitGenerator
| builtins.object
|
| Methods defined here:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce_cython__(...)
|
| __setstate_cython__(...)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| state
| Get or set the PRNG state
|
| Returns
| -------
| state : dict
| Dictionary containing the information required to describe the
| state of the PRNG
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.random.bit_generator.BitGenerator:
|
| __getstate__(self)
|
| __reduce__(self)
|
| __setstate__(self, state_seed_seq)
|
| random_raw(self, size=None, output=True)
| random_raw(self, size=None)
|
| Return randoms as generated by the underlying BitGenerator
|
| Parameters
| ----------
| size : int or tuple of ints, optional
| Output shape. If the given shape is, e.g., ``(m, n, k)``, then
| ``m * n * k`` samples are drawn. Default is None, in which case a
| single value is returned.
| output : bool, optional
| Output values. Used for performance testing since the generated
| values are not returned.
|
| Returns
| -------
| out : uint or ndarray
| Drawn samples.
|
| Notes
| -----
| This method directly exposes the raw underlying pseudo-random
| number generator. All values are returned as unsigned 64-bit
| values irrespective of the number of bits produced by the PRNG.
|
| See the class docstring for the number of bits returned.
|
| spawn(self, n_children)
| spawn(n_children)
|
| Create new independent child bit generators.
|
| See :ref:`seedsequence-spawn` for additional notes on spawning
| children. Some bit generators also implement ``jumped``
| as a different approach for creating independent streams.
|
| .. versionadded:: 1.25.0
|
| Parameters
| ----------
| n_children : int
|
| Returns
| -------
| child_bit_generators : list of BitGenerators
|
| Raises
| ------
| TypeError
| When the underlying SeedSequence does not implement spawning.
|
| See Also
| --------
| random.Generator.spawn, random.SeedSequence.spawn :
| Equivalent method on the generator and seed sequence.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.random.bit_generator.BitGenerator:
|
| capsule
|
| cffi
| CFFI interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing CFFI wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| ctypes
| ctypes interface
|
| Returns
| -------
| interface : namedtuple
| Named tuple containing ctypes wrapper
|
| * state_address - Memory address of the state struct
| * state - pointer to the state struct
| * next_uint64 - function pointer to produce 64 bit integers
| * next_uint32 - function pointer to produce 32 bit integers
| * next_double - function pointer to produce doubles
| * bitgen - pointer to the bit generator struct
|
| lock
|
| seed_seq
| Get the seed sequence used to initialize the bit generator.
|
| .. versionadded:: 1.25.0
|
| Returns
| -------
| seed_seq : ISeedSequence
| The SeedSequence object used to initialize the BitGenerator.
| This is normally a `np.random.SeedSequence` instance.
class SeedSequence(builtins.object)
| SeedSequence(entropy=None, *, spawn_key=(), pool_size=4)
|
| SeedSequence mixes sources of entropy in a reproducible way to set the
| initial state for independent and very probably non-overlapping
| BitGenerators.
|
| Once the SeedSequence is instantiated, you can call the `generate_state`
| method to get an appropriately sized seed. Calling `spawn(n) <spawn>` will
| create ``n`` SeedSequences that can be used to seed independent
| BitGenerators, i.e. for different threads.
|
| Parameters
| ----------
| entropy : {None, int, sequence[int]}, optional
| The entropy for creating a `SeedSequence`.
| All integer values must be non-negative.
| spawn_key : {(), sequence[int]}, optional
| An additional source of entropy based on the position of this
| `SeedSequence` in the tree of such objects created with the
| `SeedSequence.spawn` method. Typically, only `SeedSequence.spawn` will
| set this, and users will not.
| pool_size : {int}, optional
| Size of the pooled entropy to store. Default is 4 to give a 128-bit
| entropy pool. 8 (for 256 bits) is another reasonable choice if working
| with larger PRNGs, but there is very little to be gained by selecting
| another value.
| n_children_spawned : {int}, optional
| The number of children already spawned. Only pass this if
| reconstructing a `SeedSequence` from a serialized form.
|
| Notes
| -----
|
| Best practice for achieving reproducible bit streams is to use
| the default ``None`` for the initial entropy, and then use
| `SeedSequence.entropy` to log/pickle the `entropy` for reproducibility:
|
| >>> sq1 = np.random.SeedSequence()
| >>> sq1.entropy
| 243799254704924441050048792905230269161 # random
| >>> sq2 = np.random.SeedSequence(sq1.entropy)
| >>> np.all(sq1.generate_state(10) == sq2.generate_state(10))
| True
|
| Methods defined here:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __reduce__ = __reduce_cython__(...)
|
| __reduce_cython__(self)
|
| __repr__(...)
| Return repr(self).
|
| __setstate__ = __setstate_cython__(...)
|
| __setstate_cython__(self, __pyx_state)
|
| generate_state(self, n_words, dtype=<class 'numpy.uint32'>)
| generate_state(n_words, dtype=np.uint32)
|
| Return the requested number of words for PRNG seeding.
|
| A BitGenerator should call this method in its constructor with
| an appropriate `n_words` parameter to properly seed itself.
|
| Parameters
| ----------
| n_words : int
| dtype : np.uint32 or np.uint64, optional
| The size of each word. This should only be either `uint32` or
| `uint64`. Strings (`'uint32'`, `'uint64'`) are fine. Note that
| requesting `uint64` will draw twice as many bits as `uint32` for
| the same `n_words`. This is a convenience for `BitGenerator`\ s
| that express their states as `uint64` arrays.
|
| Returns
| -------
| state : uint32 or uint64 array, shape=(n_words,)
|
| spawn(self, n_children)
| spawn(n_children)
|
| Spawn a number of child `SeedSequence` s by extending the
| `spawn_key`.
|
| See :ref:`seedsequence-spawn` for additional notes on spawning
| children.
|
| Parameters
| ----------
| n_children : int
|
| Returns
| -------
| seqs : list of `SeedSequence` s
|
| See Also
| --------
| random.Generator.spawn, random.BitGenerator.spawn :
| Equivalent method on the generator and bit generator.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| entropy
|
| n_children_spawned
|
| pool
|
| pool_size
|
| spawn_key
|
| state
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __pyx_vtable__ = <capsule object NULL>
FUNCTIONS
beta(a, b, size=None) method of numpy.random.mtrand.RandomState instance
beta(a, b, size=None)
Draw samples from a Beta distribution.
The Beta distribution is a special case of the Dirichlet distribution,
and is related to the Gamma distribution. It has the probability
distribution function
.. math:: f(x; a,b) = \frac{1}{B(\alpha, \beta)} x^{\alpha - 1}
(1 - x)^{\beta - 1},
where the normalization, B, is the beta function,
.. math:: B(\alpha, \beta) = \int_0^1 t^{\alpha - 1}
(1 - t)^{\beta - 1} dt.
It is often seen in Bayesian inference and order statistics.
.. note::
New code should use the `~numpy.random.Generator.beta`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
a : float or array_like of floats
Alpha, positive (>0).
b : float or array_like of floats
Beta, positive (>0).
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``a`` and ``b`` are both scalars.
Otherwise, ``np.broadcast(a, b).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized beta distribution.
See Also
--------
random.Generator.beta: which should be used for new code.
binomial(n, p, size=None) method of numpy.random.mtrand.RandomState instance
binomial(n, p, size=None)
Draw samples from a binomial distribution.
Samples are drawn from a binomial distribution with specified
parameters, n trials and p probability of success where
n an integer >= 0 and p is in the interval [0,1]. (n may be
input as a float, but it is truncated to an integer in use)
.. note::
New code should use the `~numpy.random.Generator.binomial`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
n : int or array_like of ints
Parameter of the distribution, >= 0. Floats are also accepted,
but they will be truncated to integers.
p : float or array_like of floats
Parameter of the distribution, >= 0 and <=1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``n`` and ``p`` are both scalars.
Otherwise, ``np.broadcast(n, p).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized binomial distribution, where
each sample is equal to the number of successes over the n trials.
See Also
--------
scipy.stats.binom : probability density function, distribution or
cumulative density function, etc.
random.Generator.binomial: which should be used for new code.
Notes
-----
The probability density for the binomial distribution is
.. math:: P(N) = \binom{n}{N}p^N(1-p)^{n-N},
where :math:`n` is the number of trials, :math:`p` is the probability
of success, and :math:`N` is the number of successes.
When estimating the standard error of a proportion in a population by
using a random sample, the normal distribution works well unless the
product p*n <=5, where p = population proportion estimate, and n =
number of samples, in which case the binomial distribution is used
instead. For example, a sample of 15 people shows 4 who are left
handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4,
so the binomial distribution should be used in this case.
References
----------
.. [1] Dalgaard, Peter, "Introductory Statistics with R",
Springer-Verlag, 2002.
.. [2] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
Fifth Edition, 2002.
.. [3] Lentner, Marvin, "Elementary Applied Statistics", Bogden
and Quigley, 1972.
.. [4] Weisstein, Eric W. "Binomial Distribution." From MathWorld--A
Wolfram Web Resource.
https://mathworld.wolfram.com/BinomialDistribution.html
.. [5] Wikipedia, "Binomial distribution",
https://en.wikipedia.org/wiki/Binomial_distribution
Examples
--------
Draw samples from the distribution:
>>> n, p = 10, .5 # number of trials, probability of each trial
>>> s = np.random.binomial(n, p, 1000)
# result of flipping a coin 10 times, tested 1000 times.
A real world example. A company drills 9 wild-cat oil exploration
wells, each with an estimated probability of success of 0.1. All nine
wells fail. What is the probability of that happening?
Let's do 20,000 trials of the model, and count the number that
generate zero positive results.
>>> sum(np.random.binomial(9, 0.1, 20000) == 0)/20000.
# answer = 0.38885, or 38%.
bytes(length) method of numpy.random.mtrand.RandomState instance
bytes(length)
Return random bytes.
.. note::
New code should use the `~numpy.random.Generator.bytes`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
length : int
Number of random bytes.
Returns
-------
out : bytes
String of length `length`.
See Also
--------
random.Generator.bytes: which should be used for new code.
Examples
--------
>>> np.random.bytes(10)
b' eh\x85\x022SZ\xbf\xa4' #random
chisquare(df, size=None) method of numpy.random.mtrand.RandomState instance
chisquare(df, size=None)
Draw samples from a chi-square distribution.
When `df` independent random variables, each with standard normal
distributions (mean 0, variance 1), are squared and summed, the
resulting distribution is chi-square (see Notes). This distribution
is often used in hypothesis testing.
.. note::
New code should use the `~numpy.random.Generator.chisquare`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
df : float or array_like of floats
Number of degrees of freedom, must be > 0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``df`` is a scalar. Otherwise,
``np.array(df).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized chi-square distribution.
Raises
------
ValueError
When `df` <= 0 or when an inappropriate `size` (e.g. ``size=-1``)
is given.
See Also
--------
random.Generator.chisquare: which should be used for new code.
Notes
-----
The variable obtained by summing the squares of `df` independent,
standard normally distributed random variables:
.. math:: Q = \sum_{i=0}^{\mathtt{df}} X^2_i
is chi-square distributed, denoted
.. math:: Q \sim \chi^2_k.
The probability density function of the chi-squared distribution is
.. math:: p(x) = \frac{(1/2)^{k/2}}{\Gamma(k/2)}
x^{k/2 - 1} e^{-x/2},
where :math:`\Gamma` is the gamma function,
.. math:: \Gamma(x) = \int_0^{-\infty} t^{x - 1} e^{-t} dt.
References
----------
.. [1] NIST "Engineering Statistics Handbook"
https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
Examples
--------
>>> np.random.chisquare(2,4)
array([ 1.89920014, 9.00867716, 3.13710533, 5.62318272]) # random
choice(a, size=None, replace=True, p=None) method of numpy.random.mtrand.RandomState instance
choice(a, size=None, replace=True, p=None)
Generates a random sample from a given 1-D array
.. versionadded:: 1.7.0
.. note::
New code should use the `~numpy.random.Generator.choice`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
.. warning::
This function uses the C-long dtype, which is 32bit on windows
and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones).
Since NumPy 2.0, NumPy's default integer is 32bit on 32bit platforms
and 64bit on 64bit platforms.
Parameters
----------
a : 1-D array-like or int
If an ndarray, a random sample is generated from its elements.
If an int, the random sample is generated as if it were ``np.arange(a)``
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
replace : boolean, optional
Whether the sample is with or without replacement. Default is True,
meaning that a value of ``a`` can be selected multiple times.
p : 1-D array-like, optional
The probabilities associated with each entry in a.
If not given, the sample assumes a uniform distribution over all
entries in ``a``.
Returns
-------
samples : single item or ndarray
The generated random samples
Raises
------
ValueError
If a is an int and less than zero, if a or p are not 1-dimensional,
if a is an array-like of size 0, if p is not a vector of
probabilities, if a and p have different lengths, or if
replace=False and the sample size is greater than the population
size
See Also
--------
randint, shuffle, permutation
random.Generator.choice: which should be used in new code
Notes
-----
Setting user-specified probabilities through ``p`` uses a more general but less
efficient sampler than the default. The general sampler produces a different sample
than the optimized sampler even if each element of ``p`` is 1 / len(a).
Sampling random rows from a 2-D array is not possible with this function,
but is possible with `Generator.choice` through its ``axis`` keyword.
Examples
--------
Generate a uniform random sample from np.arange(5) of size 3:
>>> np.random.choice(5, 3)
array([0, 3, 4]) # random
>>> #This is equivalent to np.random.randint(0,5,3)
Generate a non-uniform random sample from np.arange(5) of size 3:
>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 3, 0]) # random
Generate a uniform random sample from np.arange(5) of size 3 without
replacement:
>>> np.random.choice(5, 3, replace=False)
array([3,1,0]) # random
>>> #This is equivalent to np.random.permutation(np.arange(5))[:3]
Generate a non-uniform random sample from np.arange(5) of size
3 without replacement:
>>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
array([2, 3, 0]) # random
Any of the above can be repeated with an arbitrary array-like
instead of just integers. For instance:
>>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
>>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'], # random
dtype='<U11')
default_rng(seed=None)
default_rng(seed=None)
Construct a new Generator with the default BitGenerator (PCG64).
Parameters
----------
seed : {None, int, array_like[ints], SeedSequence, BitGenerator, Generator}, optional
A seed to initialize the `BitGenerator`. If None, then fresh,
unpredictable entropy will be pulled from the OS. If an ``int`` or
``array_like[ints]`` is passed, then all values must be non-negative and will be
passed to `SeedSequence` to derive the initial `BitGenerator` state. One may also
pass in a `SeedSequence` instance.
Additionally, when passed a `BitGenerator`, it will be wrapped by
`Generator`. If passed a `Generator`, it will be returned unaltered.
Returns
-------
Generator
The initialized generator object.
Notes
-----
If ``seed`` is not a `BitGenerator` or a `Generator`, a new `BitGenerator`
is instantiated. This function does not manage a default global instance.
See :ref:`seeding_and_entropy` for more information about seeding.
Examples
--------
`default_rng` is the recommended constructor for the random number class
`Generator`. Here are several ways we can construct a random
number generator using `default_rng` and the `Generator` class.
Here we use `default_rng` to generate a random float:
>>> import numpy as np
>>> rng = np.random.default_rng(12345)
>>> print(rng)
Generator(PCG64)
>>> rfloat = rng.random()
>>> rfloat
0.22733602246716966
>>> type(rfloat)
<class 'float'>
Here we use `default_rng` to generate 3 random integers between 0
(inclusive) and 10 (exclusive):
>>> import numpy as np
>>> rng = np.random.default_rng(12345)
>>> rints = rng.integers(low=0, high=10, size=3)
>>> rints
array([6, 2, 7])
>>> type(rints[0])
<class 'numpy.int64'>
Here we specify a seed so that we have reproducible results:
>>> import numpy as np
>>> rng = np.random.default_rng(seed=42)
>>> print(rng)
Generator(PCG64)
>>> arr1 = rng.random((3, 3))
>>> arr1
array([[0.77395605, 0.43887844, 0.85859792],
[0.69736803, 0.09417735, 0.97562235],
[0.7611397 , 0.78606431, 0.12811363]])
If we exit and restart our Python interpreter, we'll see that we
generate the same random numbers again:
>>> import numpy as np
>>> rng = np.random.default_rng(seed=42)
>>> arr2 = rng.random((3, 3))
>>> arr2
array([[0.77395605, 0.43887844, 0.85859792],
[0.69736803, 0.09417735, 0.97562235],
[0.7611397 , 0.78606431, 0.12811363]])
dirichlet(alpha, size=None) method of numpy.random.mtrand.RandomState instance
dirichlet(alpha, size=None)
Draw samples from the Dirichlet distribution.
Draw `size` samples of dimension k from a Dirichlet distribution. A
Dirichlet-distributed random variable can be seen as a multivariate
generalization of a Beta distribution. The Dirichlet distribution
is a conjugate prior of a multinomial distribution in Bayesian
inference.
.. note::
New code should use the `~numpy.random.Generator.dirichlet`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
alpha : sequence of floats, length k
Parameter of the distribution (length ``k`` for sample of
length ``k``).
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
vector of length ``k`` is returned.
Returns
-------
samples : ndarray,
The drawn samples, of shape ``(size, k)``.
Raises
------
ValueError
If any value in ``alpha`` is less than or equal to zero
See Also
--------
random.Generator.dirichlet: which should be used for new code.
Notes
-----
The Dirichlet distribution is a distribution over vectors
:math:`x` that fulfil the conditions :math:`x_i>0` and
:math:`\sum_{i=1}^k x_i = 1`.
The probability density function :math:`p` of a
Dirichlet-distributed random vector :math:`X` is
proportional to
.. math:: p(x) \propto \prod_{i=1}^{k}{x^{\alpha_i-1}_i},
where :math:`\alpha` is a vector containing the positive
concentration parameters.
The method uses the following property for computation: let :math:`Y`
be a random vector which has components that follow a standard gamma
distribution, then :math:`X = \frac{1}{\sum_{i=1}^k{Y_i}} Y`
is Dirichlet-distributed
References
----------
.. [1] David McKay, "Information Theory, Inference and Learning
Algorithms," chapter 23,
https://www.inference.org.uk/mackay/itila/
.. [2] Wikipedia, "Dirichlet distribution",
https://en.wikipedia.org/wiki/Dirichlet_distribution
Examples
--------
Taking an example cited in Wikipedia, this distribution can be used if
one wanted to cut strings (each of initial length 1.0) into K pieces
with different lengths, where each piece had, on average, a designated
average length, but allowing some variation in the relative sizes of
the pieces.
>>> s = np.random.dirichlet((10, 5, 3), 20).transpose()
>>> import matplotlib.pyplot as plt
>>> plt.barh(range(20), s[0])
>>> plt.barh(range(20), s[1], left=s[0], color='g')
>>> plt.barh(range(20), s[2], left=s[0]+s[1], color='r')
>>> plt.title("Lengths of Strings")
exponential(scale=1.0, size=None) method of numpy.random.mtrand.RandomState instance
exponential(scale=1.0, size=None)
Draw samples from an exponential distribution.
Its probability density function is
.. math:: f(x; \frac{1}{\beta}) = \frac{1}{\beta} \exp(-\frac{x}{\beta}),
for ``x > 0`` and 0 elsewhere. :math:`\beta` is the scale parameter,
which is the inverse of the rate parameter :math:`\lambda = 1/\beta`.
The rate parameter is an alternative, widely used parameterization
of the exponential distribution [3]_.
The exponential distribution is a continuous analogue of the
geometric distribution. It describes many common situations, such as
the size of raindrops measured over many rainstorms [1]_, or the time
between page requests to Wikipedia [2]_.
.. note::
New code should use the `~numpy.random.Generator.exponential`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
scale : float or array_like of floats
The scale parameter, :math:`\beta = 1/\lambda`. Must be
non-negative.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``scale`` is a scalar. Otherwise,
``np.array(scale).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized exponential distribution.
Examples
--------
A real world example: Assume a company has 10000 customer support
agents and the average time between customer calls is 4 minutes.
>>> n = 10000
>>> time_between_calls = np.random.default_rng().exponential(scale=4, size=n)
What is the probability that a customer will call in the next
4 to 5 minutes?
>>> x = ((time_between_calls < 5).sum())/n
>>> y = ((time_between_calls < 4).sum())/n
>>> x-y
0.08 # may vary
See Also
--------
random.Generator.exponential: which should be used for new code.
References
----------
.. [1] Peyton Z. Peebles Jr., "Probability, Random Variables and
Random Signal Principles", 4th ed, 2001, p. 57.
.. [2] Wikipedia, "Poisson process",
https://en.wikipedia.org/wiki/Poisson_process
.. [3] Wikipedia, "Exponential distribution",
https://en.wikipedia.org/wiki/Exponential_distribution
f(dfnum, dfden, size=None) method of numpy.random.mtrand.RandomState instance
f(dfnum, dfden, size=None)
Draw samples from an F distribution.
Samples are drawn from an F distribution with specified parameters,
`dfnum` (degrees of freedom in numerator) and `dfden` (degrees of
freedom in denominator), where both parameters must be greater than
zero.
The random variate of the F distribution (also known as the
Fisher distribution) is a continuous probability distribution
that arises in ANOVA tests, and is the ratio of two chi-square
variates.
.. note::
New code should use the `~numpy.random.Generator.f`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
dfnum : float or array_like of floats
Degrees of freedom in numerator, must be > 0.
dfden : float or array_like of float
Degrees of freedom in denominator, must be > 0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``dfnum`` and ``dfden`` are both scalars.
Otherwise, ``np.broadcast(dfnum, dfden).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized Fisher distribution.
See Also
--------
scipy.stats.f : probability density function, distribution or
cumulative density function, etc.
random.Generator.f: which should be used for new code.
Notes
-----
The F statistic is used to compare in-group variances to between-group
variances. Calculating the distribution depends on the sampling, and
so it is a function of the respective degrees of freedom in the
problem. The variable `dfnum` is the number of samples minus one, the
between-groups degrees of freedom, while `dfden` is the within-groups
degrees of freedom, the sum of the number of samples in each group
minus the number of groups.
References
----------
.. [1] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
Fifth Edition, 2002.
.. [2] Wikipedia, "F-distribution",
https://en.wikipedia.org/wiki/F-distribution
Examples
--------
An example from Glantz[1], pp 47-40:
Two groups, children of diabetics (25 people) and children from people
without diabetes (25 controls). Fasting blood glucose was measured,
case group had a mean value of 86.1, controls had a mean value of
82.2. Standard deviations were 2.09 and 2.49 respectively. Are these
data consistent with the null hypothesis that the parents diabetic
status does not affect their children's blood glucose levels?
Calculating the F statistic from the data gives a value of 36.01.
Draw samples from the distribution:
>>> dfnum = 1. # between group degrees of freedom
>>> dfden = 48. # within groups degrees of freedom
>>> s = np.random.f(dfnum, dfden, 1000)
The lower bound for the top 1% of the samples is :
>>> np.sort(s)[-10]
7.61988120985 # random
So there is about a 1% chance that the F statistic will exceed 7.62,
the measured value is 36, so the null hypothesis is rejected at the 1%
level.
gamma(shape, scale=1.0, size=None) method of numpy.random.mtrand.RandomState instance
gamma(shape, scale=1.0, size=None)
Draw samples from a Gamma distribution.
Samples are drawn from a Gamma distribution with specified parameters,
`shape` (sometimes designated "k") and `scale` (sometimes designated
"theta"), where both parameters are > 0.
.. note::
New code should use the `~numpy.random.Generator.gamma`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
shape : float or array_like of floats
The shape of the gamma distribution. Must be non-negative.
scale : float or array_like of floats, optional
The scale of the gamma distribution. Must be non-negative.
Default is equal to 1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``shape`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(shape, scale).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized gamma distribution.
See Also
--------
scipy.stats.gamma : probability density function, distribution or
cumulative density function, etc.
random.Generator.gamma: which should be used for new code.
Notes
-----
The probability density for the Gamma distribution is
.. math:: p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},
where :math:`k` is the shape and :math:`\theta` the scale,
and :math:`\Gamma` is the Gamma function.
The Gamma distribution is often used to model the times to failure of
electronic components, and arises naturally in processes for which the
waiting times between Poisson distributed events are relevant.
References
----------
.. [1] Weisstein, Eric W. "Gamma Distribution." From MathWorld--A
Wolfram Web Resource.
https://mathworld.wolfram.com/GammaDistribution.html
.. [2] Wikipedia, "Gamma distribution",
https://en.wikipedia.org/wiki/Gamma_distribution
Examples
--------
Draw samples from the distribution:
>>> shape, scale = 2., 2. # mean=4, std=2*sqrt(2)
>>> s = np.random.gamma(shape, scale, 1000)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> import scipy.special as sps # doctest: +SKIP
>>> count, bins, ignored = plt.hist(s, 50, density=True)
>>> y = bins**(shape-1)*(np.exp(-bins/scale) / # doctest: +SKIP
... (sps.gamma(shape)*scale**shape))
>>> plt.plot(bins, y, linewidth=2, color='r') # doctest: +SKIP
>>> plt.show()
geometric(p, size=None) method of numpy.random.mtrand.RandomState instance
geometric(p, size=None)
Draw samples from the geometric distribution.
Bernoulli trials are experiments with one of two outcomes:
success or failure (an example of such an experiment is flipping
a coin). The geometric distribution models the number of trials
that must be run in order to achieve success. It is therefore
supported on the positive integers, ``k = 1, 2, ...``.
The probability mass function of the geometric distribution is
.. math:: f(k) = (1 - p)^{k - 1} p
where `p` is the probability of success of an individual trial.
.. note::
New code should use the `~numpy.random.Generator.geometric`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
p : float or array_like of floats
The probability of success of an individual trial.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``p`` is a scalar. Otherwise,
``np.array(p).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized geometric distribution.
See Also
--------
random.Generator.geometric: which should be used for new code.
Examples
--------
Draw ten thousand values from the geometric distribution,
with the probability of an individual success equal to 0.35:
>>> z = np.random.geometric(p=0.35, size=10000)
How many trials succeeded after a single run?
>>> (z == 1).sum() / 10000.
0.34889999999999999 #random
get_state(legacy=True) method of numpy.random.mtrand.RandomState instance
get_state(legacy=True)
Return a tuple representing the internal state of the generator.
For more details, see `set_state`.
Parameters
----------
legacy : bool, optional
Flag indicating to return a legacy tuple state when the BitGenerator
is MT19937, instead of a dict. Raises ValueError if the underlying
bit generator is not an instance of MT19937.
Returns
-------
out : {tuple(str, ndarray of 624 uints, int, int, float), dict}
If legacy is True, the returned tuple has the following items:
1. the string 'MT19937'.
2. a 1-D array of 624 unsigned integer keys.
3. an integer ``pos``.
4. an integer ``has_gauss``.
5. a float ``cached_gaussian``.
If `legacy` is False, or the BitGenerator is not MT19937, then
state is returned as a dictionary.
See Also
--------
set_state
Notes
-----
`set_state` and `get_state` are not needed to work with any of the
random distributions in NumPy. If the internal state is manually altered,
the user should know exactly what he/she is doing.
gumbel(loc=0.0, scale=1.0, size=None) method of numpy.random.mtrand.RandomState instance
gumbel(loc=0.0, scale=1.0, size=None)
Draw samples from a Gumbel distribution.
Draw samples from a Gumbel distribution with specified location and
scale. For more information on the Gumbel distribution, see
Notes and References below.
.. note::
New code should use the `~numpy.random.Generator.gumbel`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
loc : float or array_like of floats, optional
The location of the mode of the distribution. Default is 0.
scale : float or array_like of floats, optional
The scale parameter of the distribution. Default is 1. Must be non-
negative.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``loc`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized Gumbel distribution.
See Also
--------
scipy.stats.gumbel_l
scipy.stats.gumbel_r
scipy.stats.genextreme
weibull
random.Generator.gumbel: which should be used for new code.
Notes
-----
The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme
Value Type I) distribution is one of a class of Generalized Extreme
Value (GEV) distributions used in modeling extreme value problems.
The Gumbel is a special case of the Extreme Value Type I distribution
for maximums from distributions with "exponential-like" tails.
The probability density for the Gumbel distribution is
.. math:: p(x) = \frac{e^{-(x - \mu)/ \beta}}{\beta} e^{ -e^{-(x - \mu)/
\beta}},
where :math:`\mu` is the mode, a location parameter, and
:math:`\beta` is the scale parameter.
The Gumbel (named for German mathematician Emil Julius Gumbel) was used
very early in the hydrology literature, for modeling the occurrence of
flood events. It is also used for modeling maximum wind speed and
rainfall rates. It is a "fat-tailed" distribution - the probability of
an event in the tail of the distribution is larger than if one used a
Gaussian, hence the surprisingly frequent occurrence of 100-year
floods. Floods were initially modeled as a Gaussian process, which
underestimated the frequency of extreme events.
It is one of a class of extreme value distributions, the Generalized
Extreme Value (GEV) distributions, which also includes the Weibull and
Frechet.
The function has a mean of :math:`\mu + 0.57721\beta` and a variance
of :math:`\frac{\pi^2}{6}\beta^2`.
References
----------
.. [1] Gumbel, E. J., "Statistics of Extremes,"
New York: Columbia University Press, 1958.
.. [2] Reiss, R.-D. and Thomas, M., "Statistical Analysis of Extreme
Values from Insurance, Finance, Hydrology and Other Fields,"
Basel: Birkhauser Verlag, 2001.
Examples
--------
Draw samples from the distribution:
>>> mu, beta = 0, 0.1 # location and scale
>>> s = np.random.gumbel(mu, beta, 1000)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, density=True)
>>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
... * np.exp( -np.exp( -(bins - mu) /beta) ),
... linewidth=2, color='r')
>>> plt.show()
Show how an extreme value distribution can arise from a Gaussian process
and compare to a Gaussian:
>>> means = []
>>> maxima = []
>>> for i in range(0,1000) :
... a = np.random.normal(mu, beta, 1000)
... means.append(a.mean())
... maxima.append(a.max())
>>> count, bins, ignored = plt.hist(maxima, 30, density=True)
>>> beta = np.std(maxima) * np.sqrt(6) / np.pi
>>> mu = np.mean(maxima) - 0.57721*beta
>>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
... * np.exp(-np.exp(-(bins - mu)/beta)),
... linewidth=2, color='r')
>>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi))
... * np.exp(-(bins - mu)**2 / (2 * beta**2)),
... linewidth=2, color='g')
>>> plt.show()
hypergeometric(ngood, nbad, nsample, size=None) method of numpy.random.mtrand.RandomState instance
hypergeometric(ngood, nbad, nsample, size=None)
Draw samples from a Hypergeometric distribution.
Samples are drawn from a hypergeometric distribution with specified
parameters, `ngood` (ways to make a good selection), `nbad` (ways to make
a bad selection), and `nsample` (number of items sampled, which is less
than or equal to the sum ``ngood + nbad``).
.. note::
New code should use the
`~numpy.random.Generator.hypergeometric`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
ngood : int or array_like of ints
Number of ways to make a good selection. Must be nonnegative.
nbad : int or array_like of ints
Number of ways to make a bad selection. Must be nonnegative.
nsample : int or array_like of ints
Number of items sampled. Must be at least 1 and at most
``ngood + nbad``.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if `ngood`, `nbad`, and `nsample`
are all scalars. Otherwise, ``np.broadcast(ngood, nbad, nsample).size``
samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized hypergeometric distribution. Each
sample is the number of good items within a randomly selected subset of
size `nsample` taken from a set of `ngood` good items and `nbad` bad items.
See Also
--------
scipy.stats.hypergeom : probability density function, distribution or
cumulative density function, etc.
random.Generator.hypergeometric: which should be used for new code.
Notes
-----
The probability density for the Hypergeometric distribution is
.. math:: P(x) = \frac{\binom{g}{x}\binom{b}{n-x}}{\binom{g+b}{n}},
where :math:`0 \le x \le n` and :math:`n-b \le x \le g`
for P(x) the probability of ``x`` good results in the drawn sample,
g = `ngood`, b = `nbad`, and n = `nsample`.
Consider an urn with black and white marbles in it, `ngood` of them
are black and `nbad` are white. If you draw `nsample` balls without
replacement, then the hypergeometric distribution describes the
distribution of black balls in the drawn sample.
Note that this distribution is very similar to the binomial
distribution, except that in this case, samples are drawn without
replacement, whereas in the Binomial case samples are drawn with
replacement (or the sample space is infinite). As the sample space
becomes large, this distribution approaches the binomial.
References
----------
.. [1] Lentner, Marvin, "Elementary Applied Statistics", Bogden
and Quigley, 1972.
.. [2] Weisstein, Eric W. "Hypergeometric Distribution." From
MathWorld--A Wolfram Web Resource.
https://mathworld.wolfram.com/HypergeometricDistribution.html
.. [3] Wikipedia, "Hypergeometric distribution",
https://en.wikipedia.org/wiki/Hypergeometric_distribution
Examples
--------
Draw samples from the distribution:
>>> ngood, nbad, nsamp = 100, 2, 10
# number of good, number of bad, and number of samples
>>> s = np.random.hypergeometric(ngood, nbad, nsamp, 1000)
>>> from matplotlib.pyplot import hist
>>> hist(s)
# note that it is very unlikely to grab both bad items
Suppose you have an urn with 15 white and 15 black marbles.
If you pull 15 marbles at random, how likely is it that
12 or more of them are one color?
>>> s = np.random.hypergeometric(15, 15, 15, 100000)
>>> sum(s>=12)/100000. + sum(s<=3)/100000.
# answer = 0.003 ... pretty unlikely!
laplace(loc=0.0, scale=1.0, size=None) method of numpy.random.mtrand.RandomState instance
laplace(loc=0.0, scale=1.0, size=None)
Draw samples from the Laplace or double exponential distribution with
specified location (or mean) and scale (decay).
The Laplace distribution is similar to the Gaussian/normal distribution,
but is sharper at the peak and has fatter tails. It represents the
difference between two independent, identically distributed exponential
random variables.
.. note::
New code should use the `~numpy.random.Generator.laplace`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
loc : float or array_like of floats, optional
The position, :math:`\mu`, of the distribution peak. Default is 0.
scale : float or array_like of floats, optional
:math:`\lambda`, the exponential decay. Default is 1. Must be non-
negative.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``loc`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized Laplace distribution.
See Also
--------
random.Generator.laplace: which should be used for new code.
Notes
-----
It has the probability density function
.. math:: f(x; \mu, \lambda) = \frac{1}{2\lambda}
\exp\left(-\frac{|x - \mu|}{\lambda}\right).
The first law of Laplace, from 1774, states that the frequency
of an error can be expressed as an exponential function of the
absolute magnitude of the error, which leads to the Laplace
distribution. For many problems in economics and health
sciences, this distribution seems to model the data better
than the standard Gaussian distribution.
References
----------
.. [1] Abramowitz, M. and Stegun, I. A. (Eds.). "Handbook of
Mathematical Functions with Formulas, Graphs, and Mathematical
Tables, 9th printing," New York: Dover, 1972.
.. [2] Kotz, Samuel, et. al. "The Laplace Distribution and
Generalizations, " Birkhauser, 2001.
.. [3] Weisstein, Eric W. "Laplace Distribution."
From MathWorld--A Wolfram Web Resource.
https://mathworld.wolfram.com/LaplaceDistribution.html
.. [4] Wikipedia, "Laplace distribution",
https://en.wikipedia.org/wiki/Laplace_distribution
Examples
--------
Draw samples from the distribution
>>> loc, scale = 0., 1.
>>> s = np.random.laplace(loc, scale, 1000)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, density=True)
>>> x = np.arange(-8., 8., .01)
>>> pdf = np.exp(-abs(x-loc)/scale)/(2.*scale)
>>> plt.plot(x, pdf)
Plot Gaussian for comparison:
>>> g = (1/(scale * np.sqrt(2 * np.pi)) *
... np.exp(-(x - loc)**2 / (2 * scale**2)))
>>> plt.plot(x,g)
logistic(loc=0.0, scale=1.0, size=None) method of numpy.random.mtrand.RandomState instance
logistic(loc=0.0, scale=1.0, size=None)
Draw samples from a logistic distribution.
Samples are drawn from a logistic distribution with specified
parameters, loc (location or mean, also median), and scale (>0).
.. note::
New code should use the `~numpy.random.Generator.logistic`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
loc : float or array_like of floats, optional
Parameter of the distribution. Default is 0.
scale : float or array_like of floats, optional
Parameter of the distribution. Must be non-negative.
Default is 1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``loc`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized logistic distribution.
See Also
--------
scipy.stats.logistic : probability density function, distribution or
cumulative density function, etc.
random.Generator.logistic: which should be used for new code.
Notes
-----
The probability density for the Logistic distribution is
.. math:: P(x) = P(x) = \frac{e^{-(x-\mu)/s}}{s(1+e^{-(x-\mu)/s})^2},
where :math:`\mu` = location and :math:`s` = scale.
The Logistic distribution is used in Extreme Value problems where it
can act as a mixture of Gumbel distributions, in Epidemiology, and by
the World Chess Federation (FIDE) where it is used in the Elo ranking
system, assuming the performance of each player is a logistically
distributed random variable.
References
----------
.. [1] Reiss, R.-D. and Thomas M. (2001), "Statistical Analysis of
Extreme Values, from Insurance, Finance, Hydrology and Other
Fields," Birkhauser Verlag, Basel, pp 132-133.
.. [2] Weisstein, Eric W. "Logistic Distribution." From
MathWorld--A Wolfram Web Resource.
https://mathworld.wolfram.com/LogisticDistribution.html
.. [3] Wikipedia, "Logistic-distribution",
https://en.wikipedia.org/wiki/Logistic_distribution
Examples
--------
Draw samples from the distribution:
>>> loc, scale = 10, 1
>>> s = np.random.logistic(loc, scale, 10000)
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, bins=50)
# plot against distribution
>>> def logist(x, loc, scale):
... return np.exp((loc-x)/scale)/(scale*(1+np.exp((loc-x)/scale))**2)
>>> lgst_val = logist(bins, loc, scale)
>>> plt.plot(bins, lgst_val * count.max() / lgst_val.max())
>>> plt.show()
lognormal(mean=0.0, sigma=1.0, size=None) method of numpy.random.mtrand.RandomState instance
lognormal(mean=0.0, sigma=1.0, size=None)
Draw samples from a log-normal distribution.
Draw samples from a log-normal distribution with specified mean,
standard deviation, and array shape. Note that the mean and standard
deviation are not the values for the distribution itself, but of the
underlying normal distribution it is derived from.
.. note::
New code should use the `~numpy.random.Generator.lognormal`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
mean : float or array_like of floats, optional
Mean value of the underlying normal distribution. Default is 0.
sigma : float or array_like of floats, optional
Standard deviation of the underlying normal distribution. Must be
non-negative. Default is 1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``mean`` and ``sigma`` are both scalars.
Otherwise, ``np.broadcast(mean, sigma).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized log-normal distribution.
See Also
--------
scipy.stats.lognorm : probability density function, distribution,
cumulative density function, etc.
random.Generator.lognormal: which should be used for new code.
Notes
-----
A variable `x` has a log-normal distribution if `log(x)` is normally
distributed. The probability density function for the log-normal
distribution is:
.. math:: p(x) = \frac{1}{\sigma x \sqrt{2\pi}}
e^{(-\frac{(ln(x)-\mu)^2}{2\sigma^2})}
where :math:`\mu` is the mean and :math:`\sigma` is the standard
deviation of the normally distributed logarithm of the variable.
A log-normal distribution results if a random variable is the *product*
of a large number of independent, identically-distributed variables in
the same way that a normal distribution results if the variable is the
*sum* of a large number of independent, identically-distributed
variables.
References
----------
.. [1] Limpert, E., Stahel, W. A., and Abbt, M., "Log-normal
Distributions across the Sciences: Keys and Clues,"
BioScience, Vol. 51, No. 5, May, 2001.
https://stat.ethz.ch/~stahel/lognormal/bioscience.pdf
.. [2] Reiss, R.D. and Thomas, M., "Statistical Analysis of Extreme
Values," Basel: Birkhauser Verlag, 2001, pp. 31-32.
Examples
--------
Draw samples from the distribution:
>>> mu, sigma = 3., 1. # mean and standard deviation
>>> s = np.random.lognormal(mu, sigma, 1000)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 100, density=True, align='mid')
>>> x = np.linspace(min(bins), max(bins), 10000)
>>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
... / (x * sigma * np.sqrt(2 * np.pi)))
>>> plt.plot(x, pdf, linewidth=2, color='r')
>>> plt.axis('tight')
>>> plt.show()
Demonstrate that taking the products of random samples from a uniform
distribution can be fit well by a log-normal probability density
function.
>>> # Generate a thousand samples: each is the product of 100 random
>>> # values, drawn from a normal distribution.
>>> b = []
>>> for i in range(1000):
... a = 10. + np.random.standard_normal(100)
... b.append(np.prod(a))
>>> b = np.array(b) / np.min(b) # scale values to be positive
>>> count, bins, ignored = plt.hist(b, 100, density=True, align='mid')
>>> sigma = np.std(np.log(b))
>>> mu = np.mean(np.log(b))
>>> x = np.linspace(min(bins), max(bins), 10000)
>>> pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
... / (x * sigma * np.sqrt(2 * np.pi)))
>>> plt.plot(x, pdf, color='r', linewidth=2)
>>> plt.show()
logseries(p, size=None) method of numpy.random.mtrand.RandomState instance
logseries(p, size=None)
Draw samples from a logarithmic series distribution.
Samples are drawn from a log series distribution with specified
shape parameter, 0 <= ``p`` < 1.
.. note::
New code should use the `~numpy.random.Generator.logseries`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
p : float or array_like of floats
Shape parameter for the distribution. Must be in the range [0, 1).
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``p`` is a scalar. Otherwise,
``np.array(p).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized logarithmic series distribution.
See Also
--------
scipy.stats.logser : probability density function, distribution or
cumulative density function, etc.
random.Generator.logseries: which should be used for new code.
Notes
-----
The probability density for the Log Series distribution is
.. math:: P(k) = \frac{-p^k}{k \ln(1-p)},
where p = probability.
The log series distribution is frequently used to represent species
richness and occurrence, first proposed by Fisher, Corbet, and
Williams in 1943 [2]. It may also be used to model the numbers of
occupants seen in cars [3].
References
----------
.. [1] Buzas, Martin A.; Culver, Stephen J., Understanding regional
species diversity through the log series distribution of
occurrences: BIODIVERSITY RESEARCH Diversity & Distributions,
Volume 5, Number 5, September 1999 , pp. 187-195(9).
.. [2] Fisher, R.A,, A.S. Corbet, and C.B. Williams. 1943. The
relation between the number of species and the number of
individuals in a random sample of an animal population.
Journal of Animal Ecology, 12:42-58.
.. [3] D. J. Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small
Data Sets, CRC Press, 1994.
.. [4] Wikipedia, "Logarithmic distribution",
https://en.wikipedia.org/wiki/Logarithmic_distribution
Examples
--------
Draw samples from the distribution:
>>> a = .6
>>> s = np.random.logseries(a, 10000)
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s)
# plot against distribution
>>> def logseries(k, p):
... return -p**k/(k*np.log(1-p))
>>> plt.plot(bins, logseries(bins, a)*count.max()/
... logseries(bins, a).max(), 'r')
>>> plt.show()
multinomial(n, pvals, size=None) method of numpy.random.mtrand.RandomState instance
multinomial(n, pvals, size=None)
Draw samples from a multinomial distribution.
The multinomial distribution is a multivariate generalization of the
binomial distribution. Take an experiment with one of ``p``
possible outcomes. An example of such an experiment is throwing a dice,
where the outcome can be 1 through 6. Each sample drawn from the
distribution represents `n` such experiments. Its values,
``X_i = [X_0, X_1, ..., X_p]``, represent the number of times the
outcome was ``i``.
.. note::
New code should use the `~numpy.random.Generator.multinomial`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
.. warning::
This function defaults to the C-long dtype, which is 32bit on windows
and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones).
Since NumPy 2.0, NumPy's default integer is 32bit on 32bit platforms
and 64bit on 64bit platforms.
Parameters
----------
n : int
Number of experiments.
pvals : sequence of floats, length p
Probabilities of each of the ``p`` different outcomes. These
must sum to 1 (however, the last element is always assumed to
account for the remaining probability, as long as
``sum(pvals[:-1]) <= 1)``.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
Returns
-------
out : ndarray
The drawn samples, of shape *size*, if that was provided. If not,
the shape is ``(N,)``.
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
value drawn from the distribution.
See Also
--------
random.Generator.multinomial: which should be used for new code.
Examples
--------
Throw a dice 20 times:
>>> np.random.multinomial(20, [1/6.]*6, size=1)
array([[4, 1, 7, 5, 2, 1]]) # random
It landed 4 times on 1, once on 2, etc.
Now, throw the dice 20 times, and 20 times again:
>>> np.random.multinomial(20, [1/6.]*6, size=2)
array([[3, 4, 3, 3, 4, 3], # random
[2, 4, 3, 4, 0, 7]])
For the first run, we threw 3 times 1, 4 times 2, etc. For the second,
we threw 2 times 1, 4 times 2, etc.
A loaded die is more likely to land on number 6:
>>> np.random.multinomial(100, [1/7.]*5 + [2/7.])
array([11, 16, 14, 17, 16, 26]) # random
The probability inputs should be normalized. As an implementation
detail, the value of the last entry is ignored and assumed to take
up any leftover probability mass, but this should not be relied on.
A biased coin which has twice as much weight on one side as on the
other should be sampled like so:
>>> np.random.multinomial(100, [1.0 / 3, 2.0 / 3]) # RIGHT
array([38, 62]) # random
not like:
>>> np.random.multinomial(100, [1.0, 2.0]) # WRONG
Traceback (most recent call last):
ValueError: pvals < 0, pvals > 1 or pvals contains NaNs
multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-08) method of numpy.random.mtrand.RandomState instance
multivariate_normal(mean, cov, size=None, check_valid='warn', tol=1e-8)
Draw random samples from a multivariate normal distribution.
The multivariate normal, multinormal or Gaussian distribution is a
generalization of the one-dimensional normal distribution to higher
dimensions. Such a distribution is specified by its mean and
covariance matrix. These parameters are analogous to the mean
(average or "center") and variance (standard deviation, or "width,"
squared) of the one-dimensional normal distribution.
.. note::
New code should use the
`~numpy.random.Generator.multivariate_normal`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
mean : 1-D array_like, of length N
Mean of the N-dimensional distribution.
cov : 2-D array_like, of shape (N, N)
Covariance matrix of the distribution. It must be symmetric and
positive-semidefinite for proper sampling.
size : int or tuple of ints, optional
Given a shape of, for example, ``(m,n,k)``, ``m*n*k`` samples are
generated, and packed in an `m`-by-`n`-by-`k` arrangement. Because
each sample is `N`-dimensional, the output shape is ``(m,n,k,N)``.
If no shape is specified, a single (`N`-D) sample is returned.
check_valid : { 'warn', 'raise', 'ignore' }, optional
Behavior when the covariance matrix is not positive semidefinite.
tol : float, optional
Tolerance when checking the singular values in covariance matrix.
cov is cast to double before the check.
Returns
-------
out : ndarray
The drawn samples, of shape *size*, if that was provided. If not,
the shape is ``(N,)``.
In other words, each entry ``out[i,j,...,:]`` is an N-dimensional
value drawn from the distribution.
See Also
--------
random.Generator.multivariate_normal: which should be used for new code.
Notes
-----
The mean is a coordinate in N-dimensional space, which represents the
location where samples are most likely to be generated. This is
analogous to the peak of the bell curve for the one-dimensional or
univariate normal distribution.
Covariance indicates the level to which two variables vary together.
From the multivariate normal distribution, we draw N-dimensional
samples, :math:`X = [x_1, x_2, ... x_N]`. The covariance matrix
element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`.
The element :math:`C_{ii}` is the variance of :math:`x_i` (i.e. its
"spread").
Instead of specifying the full covariance matrix, popular
approximations include:
- Spherical covariance (`cov` is a multiple of the identity matrix)
- Diagonal covariance (`cov` has non-negative elements, and only on
the diagonal)
This geometrical property can be seen in two dimensions by plotting
generated data-points:
>>> mean = [0, 0]
>>> cov = [[1, 0], [0, 100]] # diagonal covariance
Diagonal covariance means that points are oriented along x or y-axis:
>>> import matplotlib.pyplot as plt
>>> x, y = np.random.multivariate_normal(mean, cov, 5000).T
>>> plt.plot(x, y, 'x')
>>> plt.axis('equal')
>>> plt.show()
Note that the covariance matrix must be positive semidefinite (a.k.a.
nonnegative-definite). Otherwise, the behavior of this method is
undefined and backwards compatibility is not guaranteed.
References
----------
.. [1] Papoulis, A., "Probability, Random Variables, and Stochastic
Processes," 3rd ed., New York: McGraw-Hill, 1991.
.. [2] Duda, R. O., Hart, P. E., and Stork, D. G., "Pattern
Classification," 2nd ed., New York: Wiley, 2001.
Examples
--------
>>> mean = (1, 2)
>>> cov = [[1, 0], [0, 1]]
>>> x = np.random.multivariate_normal(mean, cov, (3, 3))
>>> x.shape
(3, 3, 2)
Here we generate 800 samples from the bivariate normal distribution
with mean [0, 0] and covariance matrix [[6, -3], [-3, 3.5]]. The
expected variances of the first and second components of the sample
are 6 and 3.5, respectively, and the expected correlation
coefficient is -3/sqrt(6*3.5) ≈ -0.65465.
>>> cov = np.array([[6, -3], [-3, 3.5]])
>>> pts = np.random.multivariate_normal([0, 0], cov, size=800)
Check that the mean, covariance, and correlation coefficient of the
sample are close to the expected values:
>>> pts.mean(axis=0)
array([ 0.0326911 , -0.01280782]) # may vary
>>> np.cov(pts.T)
array([[ 5.96202397, -2.85602287],
[-2.85602287, 3.47613949]]) # may vary
>>> np.corrcoef(pts.T)[0, 1]
-0.6273591314603949 # may vary
We can visualize this data with a scatter plot. The orientation
of the point cloud illustrates the negative correlation of the
components of this sample.
>>> import matplotlib.pyplot as plt
>>> plt.plot(pts[:, 0], pts[:, 1], '.', alpha=0.5)
>>> plt.axis('equal')
>>> plt.grid()
>>> plt.show()
negative_binomial(n, p, size=None) method of numpy.random.mtrand.RandomState instance
negative_binomial(n, p, size=None)
Draw samples from a negative binomial distribution.
Samples are drawn from a negative binomial distribution with specified
parameters, `n` successes and `p` probability of success where `n`
is > 0 and `p` is in the interval [0, 1].
.. note::
New code should use the
`~numpy.random.Generator.negative_binomial`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
n : float or array_like of floats
Parameter of the distribution, > 0.
p : float or array_like of floats
Parameter of the distribution, >= 0 and <=1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``n`` and ``p`` are both scalars.
Otherwise, ``np.broadcast(n, p).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized negative binomial distribution,
where each sample is equal to N, the number of failures that
occurred before a total of n successes was reached.
.. warning::
This function returns the C-long dtype, which is 32bit on windows
and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones).
Since NumPy 2.0, NumPy's default integer is 32bit on 32bit platforms
and 64bit on 64bit platforms.
See Also
--------
random.Generator.negative_binomial: which should be used for new code.
Notes
-----
The probability mass function of the negative binomial distribution is
.. math:: P(N;n,p) = \frac{\Gamma(N+n)}{N!\Gamma(n)}p^{n}(1-p)^{N},
where :math:`n` is the number of successes, :math:`p` is the
probability of success, :math:`N+n` is the number of trials, and
:math:`\Gamma` is the gamma function. When :math:`n` is an integer,
:math:`\frac{\Gamma(N+n)}{N!\Gamma(n)} = \binom{N+n-1}{N}`, which is
the more common form of this term in the pmf. The negative
binomial distribution gives the probability of N failures given n
successes, with a success on the last trial.
If one throws a die repeatedly until the third time a "1" appears,
then the probability distribution of the number of non-"1"s that
appear before the third "1" is a negative binomial distribution.
References
----------
.. [1] Weisstein, Eric W. "Negative Binomial Distribution." From
MathWorld--A Wolfram Web Resource.
https://mathworld.wolfram.com/NegativeBinomialDistribution.html
.. [2] Wikipedia, "Negative binomial distribution",
https://en.wikipedia.org/wiki/Negative_binomial_distribution
Examples
--------
Draw samples from the distribution:
A real world example. A company drills wild-cat oil
exploration wells, each with an estimated probability of
success of 0.1. What is the probability of having one success
for each successive well, that is what is the probability of a
single success after drilling 5 wells, after 6 wells, etc.?
>>> s = np.random.negative_binomial(1, 0.1, 100000)
>>> for i in range(1, 11): # doctest: +SKIP
... probability = sum(s<i) / 100000.
... print(i, "wells drilled, probability of one success =", probability)
noncentral_chisquare(df, nonc, size=None) method of numpy.random.mtrand.RandomState instance
noncentral_chisquare(df, nonc, size=None)
Draw samples from a noncentral chi-square distribution.
The noncentral :math:`\chi^2` distribution is a generalization of
the :math:`\chi^2` distribution.
.. note::
New code should use the
`~numpy.random.Generator.noncentral_chisquare`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
df : float or array_like of floats
Degrees of freedom, must be > 0.
.. versionchanged:: 1.10.0
Earlier NumPy versions required dfnum > 1.
nonc : float or array_like of floats
Non-centrality, must be non-negative.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``df`` and ``nonc`` are both scalars.
Otherwise, ``np.broadcast(df, nonc).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized noncentral chi-square distribution.
See Also
--------
random.Generator.noncentral_chisquare: which should be used for new code.
Notes
-----
The probability density function for the noncentral Chi-square
distribution is
.. math:: P(x;df,nonc) = \sum^{\infty}_{i=0}
\frac{e^{-nonc/2}(nonc/2)^{i}}{i!}
P_{Y_{df+2i}}(x),
where :math:`Y_{q}` is the Chi-square with q degrees of freedom.
References
----------
.. [1] Wikipedia, "Noncentral chi-squared distribution"
https://en.wikipedia.org/wiki/Noncentral_chi-squared_distribution
Examples
--------
Draw values from the distribution and plot the histogram
>>> import matplotlib.pyplot as plt
>>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),
... bins=200, density=True)
>>> plt.show()
Draw values from a noncentral chisquare with very small noncentrality,
and compare to a chisquare.
>>> plt.figure()
>>> values = plt.hist(np.random.noncentral_chisquare(3, .0000001, 100000),
... bins=np.arange(0., 25, .1), density=True)
>>> values2 = plt.hist(np.random.chisquare(3, 100000),
... bins=np.arange(0., 25, .1), density=True)
>>> plt.plot(values[1][0:-1], values[0]-values2[0], 'ob')
>>> plt.show()
Demonstrate how large values of non-centrality lead to a more symmetric
distribution.
>>> plt.figure()
>>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),
... bins=200, density=True)
>>> plt.show()
noncentral_f(dfnum, dfden, nonc, size=None) method of numpy.random.mtrand.RandomState instance
noncentral_f(dfnum, dfden, nonc, size=None)
Draw samples from the noncentral F distribution.
Samples are drawn from an F distribution with specified parameters,
`dfnum` (degrees of freedom in numerator) and `dfden` (degrees of
freedom in denominator), where both parameters > 1.
`nonc` is the non-centrality parameter.
.. note::
New code should use the
`~numpy.random.Generator.noncentral_f`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
dfnum : float or array_like of floats
Numerator degrees of freedom, must be > 0.
.. versionchanged:: 1.14.0
Earlier NumPy versions required dfnum > 1.
dfden : float or array_like of floats
Denominator degrees of freedom, must be > 0.
nonc : float or array_like of floats
Non-centrality parameter, the sum of the squares of the numerator
means, must be >= 0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``dfnum``, ``dfden``, and ``nonc``
are all scalars. Otherwise, ``np.broadcast(dfnum, dfden, nonc).size``
samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized noncentral Fisher distribution.
See Also
--------
random.Generator.noncentral_f: which should be used for new code.
Notes
-----
When calculating the power of an experiment (power = probability of
rejecting the null hypothesis when a specific alternative is true) the
non-central F statistic becomes important. When the null hypothesis is
true, the F statistic follows a central F distribution. When the null
hypothesis is not true, then it follows a non-central F statistic.
References
----------
.. [1] Weisstein, Eric W. "Noncentral F-Distribution."
From MathWorld--A Wolfram Web Resource.
https://mathworld.wolfram.com/NoncentralF-Distribution.html
.. [2] Wikipedia, "Noncentral F-distribution",
https://en.wikipedia.org/wiki/Noncentral_F-distribution
Examples
--------
In a study, testing for a specific alternative to the null hypothesis
requires use of the Noncentral F distribution. We need to calculate the
area in the tail of the distribution that exceeds the value of the F
distribution for the null hypothesis. We'll plot the two probability
distributions for comparison.
>>> dfnum = 3 # between group deg of freedom
>>> dfden = 20 # within groups degrees of freedom
>>> nonc = 3.0
>>> nc_vals = np.random.noncentral_f(dfnum, dfden, nonc, 1000000)
>>> NF = np.histogram(nc_vals, bins=50, density=True)
>>> c_vals = np.random.f(dfnum, dfden, 1000000)
>>> F = np.histogram(c_vals, bins=50, density=True)
>>> import matplotlib.pyplot as plt
>>> plt.plot(F[1][1:], F[0])
>>> plt.plot(NF[1][1:], NF[0])
>>> plt.show()
normal(loc=0.0, scale=1.0, size=None) method of numpy.random.mtrand.RandomState instance
normal(loc=0.0, scale=1.0, size=None)
Draw random samples from a normal (Gaussian) distribution.
The probability density function of the normal distribution, first
derived by De Moivre and 200 years later by both Gauss and Laplace
independently [2]_, is often called the bell curve because of
its characteristic shape (see the example below).
The normal distributions occurs often in nature. For example, it
describes the commonly occurring distribution of samples influenced
by a large number of tiny, random disturbances, each with its own
unique distribution [2]_.
.. note::
New code should use the `~numpy.random.Generator.normal`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
loc : float or array_like of floats
Mean ("centre") of the distribution.
scale : float or array_like of floats
Standard deviation (spread or "width") of the distribution. Must be
non-negative.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``loc`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized normal distribution.
See Also
--------
scipy.stats.norm : probability density function, distribution or
cumulative density function, etc.
random.Generator.normal: which should be used for new code.
Notes
-----
The probability density for the Gaussian distribution is
.. math:: p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }}
e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },
where :math:`\mu` is the mean and :math:`\sigma` the standard
deviation. The square of the standard deviation, :math:`\sigma^2`,
is called the variance.
The function has its peak at the mean, and its "spread" increases with
the standard deviation (the function reaches 0.607 times its maximum at
:math:`x + \sigma` and :math:`x - \sigma` [2]_). This implies that
normal is more likely to return samples lying close to the mean, rather
than those far away.
References
----------
.. [1] Wikipedia, "Normal distribution",
https://en.wikipedia.org/wiki/Normal_distribution
.. [2] P. R. Peebles Jr., "Central Limit Theorem" in "Probability,
Random Variables and Random Signal Principles", 4th ed., 2001,
pp. 51, 51, 125.
Examples
--------
Draw samples from the distribution:
>>> mu, sigma = 0, 0.1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, 1000)
Verify the mean and the variance:
>>> abs(mu - np.mean(s))
0.0 # may vary
>>> abs(sigma - np.std(s, ddof=1))
0.1 # may vary
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 30, density=True)
>>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
... np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
... linewidth=2, color='r')
>>> plt.show()
Two-by-four array of samples from the normal distribution with
mean 3 and standard deviation 2.5:
>>> np.random.normal(3, 2.5, size=(2, 4))
array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random
[ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random
pareto(a, size=None) method of numpy.random.mtrand.RandomState instance
pareto(a, size=None)
Draw samples from a Pareto II or Lomax distribution with
specified shape.
The Lomax or Pareto II distribution is a shifted Pareto
distribution. The classical Pareto distribution can be
obtained from the Lomax distribution by adding 1 and
multiplying by the scale parameter ``m`` (see Notes). The
smallest value of the Lomax distribution is zero while for the
classical Pareto distribution it is ``mu``, where the standard
Pareto distribution has location ``mu = 1``. Lomax can also
be considered as a simplified version of the Generalized
Pareto distribution (available in SciPy), with the scale set
to one and the location set to zero.
The Pareto distribution must be greater than zero, and is
unbounded above. It is also known as the "80-20 rule". In
this distribution, 80 percent of the weights are in the lowest
20 percent of the range, while the other 20 percent fill the
remaining 80 percent of the range.
.. note::
New code should use the `~numpy.random.Generator.pareto`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
a : float or array_like of floats
Shape of the distribution. Must be positive.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``a`` is a scalar. Otherwise,
``np.array(a).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized Pareto distribution.
See Also
--------
scipy.stats.lomax : probability density function, distribution or
cumulative density function, etc.
scipy.stats.genpareto : probability density function, distribution or
cumulative density function, etc.
random.Generator.pareto: which should be used for new code.
Notes
-----
The probability density for the Pareto distribution is
.. math:: p(x) = \frac{am^a}{x^{a+1}}
where :math:`a` is the shape and :math:`m` the scale.
The Pareto distribution, named after the Italian economist
Vilfredo Pareto, is a power law probability distribution
useful in many real world problems. Outside the field of
economics it is generally referred to as the Bradford
distribution. Pareto developed the distribution to describe
the distribution of wealth in an economy. It has also found
use in insurance, web page access statistics, oil field sizes,
and many other problems, including the download frequency for
projects in Sourceforge [1]_. It is one of the so-called
"fat-tailed" distributions.
References
----------
.. [1] Francis Hunt and Paul Johnson, On the Pareto Distribution of
Sourceforge projects.
.. [2] Pareto, V. (1896). Course of Political Economy. Lausanne.
.. [3] Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme
Values, Birkhauser Verlag, Basel, pp 23-30.
.. [4] Wikipedia, "Pareto distribution",
https://en.wikipedia.org/wiki/Pareto_distribution
Examples
--------
Draw samples from the distribution:
>>> a, m = 3., 2. # shape and mode
>>> s = (np.random.pareto(a, 1000) + 1) * m
Display the histogram of the samples, along with the probability
density function:
>>> import matplotlib.pyplot as plt
>>> count, bins, _ = plt.hist(s, 100, density=True)
>>> fit = a*m**a / bins**(a+1)
>>> plt.plot(bins, max(count)*fit/max(fit), linewidth=2, color='r')
>>> plt.show()
permutation(x) method of numpy.random.mtrand.RandomState instance
permutation(x)
Randomly permute a sequence, or return a permuted range.
If `x` is a multi-dimensional array, it is only shuffled along its
first index.
.. note::
New code should use the
`~numpy.random.Generator.permutation`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
x : int or array_like
If `x` is an integer, randomly permute ``np.arange(x)``.
If `x` is an array, make a copy and shuffle the elements
randomly.
Returns
-------
out : ndarray
Permuted sequence or array range.
See Also
--------
random.Generator.permutation: which should be used for new code.
Examples
--------
>>> np.random.permutation(10)
array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6]) # random
>>> np.random.permutation([1, 4, 9, 12, 15])
array([15, 1, 9, 4, 12]) # random
>>> arr = np.arange(9).reshape((3, 3))
>>> np.random.permutation(arr)
array([[6, 7, 8], # random
[0, 1, 2],
[3, 4, 5]])
poisson(lam=1.0, size=None) method of numpy.random.mtrand.RandomState instance
poisson(lam=1.0, size=None)
Draw samples from a Poisson distribution.
The Poisson distribution is the limit of the binomial distribution
for large N.
.. note::
New code should use the `~numpy.random.Generator.poisson`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
lam : float or array_like of floats
Expected number of events occurring in a fixed-time interval,
must be >= 0. A sequence must be broadcastable over the requested
size.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``lam`` is a scalar. Otherwise,
``np.array(lam).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized Poisson distribution.
See Also
--------
random.Generator.poisson: which should be used for new code.
Notes
-----
The Poisson distribution
.. math:: f(k; \lambda)=\frac{\lambda^k e^{-\lambda}}{k!}
For events with an expected separation :math:`\lambda` the Poisson
distribution :math:`f(k; \lambda)` describes the probability of
:math:`k` events occurring within the observed
interval :math:`\lambda`.
Because the output is limited to the range of the C int64 type, a
ValueError is raised when `lam` is within 10 sigma of the maximum
representable value.
References
----------
.. [1] Weisstein, Eric W. "Poisson Distribution."
From MathWorld--A Wolfram Web Resource.
https://mathworld.wolfram.com/PoissonDistribution.html
.. [2] Wikipedia, "Poisson distribution",
https://en.wikipedia.org/wiki/Poisson_distribution
Examples
--------
Draw samples from the distribution:
>>> import numpy as np
>>> s = np.random.poisson(5, 10000)
Display histogram of the sample:
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 14, density=True)
>>> plt.show()
Draw each 100 values for lambda 100 and 500:
>>> s = np.random.poisson(lam=(100., 500.), size=(100, 2))
power(a, size=None) method of numpy.random.mtrand.RandomState instance
power(a, size=None)
Draws samples in [0, 1] from a power distribution with positive
exponent a - 1.
Also known as the power function distribution.
.. note::
New code should use the `~numpy.random.Generator.power`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
a : float or array_like of floats
Parameter of the distribution. Must be non-negative.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``a`` is a scalar. Otherwise,
``np.array(a).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized power distribution.
Raises
------
ValueError
If a <= 0.
See Also
--------
random.Generator.power: which should be used for new code.
Notes
-----
The probability density function is
.. math:: P(x; a) = ax^{a-1}, 0 \le x \le 1, a>0.
The power function distribution is just the inverse of the Pareto
distribution. It may also be seen as a special case of the Beta
distribution.
It is used, for example, in modeling the over-reporting of insurance
claims.
References
----------
.. [1] Christian Kleiber, Samuel Kotz, "Statistical size distributions
in economics and actuarial sciences", Wiley, 2003.
.. [2] Heckert, N. A. and Filliben, James J. "NIST Handbook 148:
Dataplot Reference Manual, Volume 2: Let Subcommands and Library
Functions", National Institute of Standards and Technology
Handbook Series, June 2003.
https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/powpdf.pdf
Examples
--------
Draw samples from the distribution:
>>> a = 5. # shape
>>> samples = 1000
>>> s = np.random.power(a, samples)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, bins=30)
>>> x = np.linspace(0, 1, 100)
>>> y = a*x**(a-1.)
>>> normed_y = samples*np.diff(bins)[0]*y
>>> plt.plot(x, normed_y)
>>> plt.show()
Compare the power function distribution to the inverse of the Pareto.
>>> from scipy import stats # doctest: +SKIP
>>> rvs = np.random.power(5, 1000000)
>>> rvsp = np.random.pareto(5, 1000000)
>>> xx = np.linspace(0,1,100)
>>> powpdf = stats.powerlaw.pdf(xx,5) # doctest: +SKIP
>>> plt.figure()
>>> plt.hist(rvs, bins=50, density=True)
>>> plt.plot(xx,powpdf,'r-') # doctest: +SKIP
>>> plt.title('np.random.power(5)')
>>> plt.figure()
>>> plt.hist(1./(1.+rvsp), bins=50, density=True)
>>> plt.plot(xx,powpdf,'r-') # doctest: +SKIP
>>> plt.title('inverse of 1 + np.random.pareto(5)')
>>> plt.figure()
>>> plt.hist(1./(1.+rvsp), bins=50, density=True)
>>> plt.plot(xx,powpdf,'r-') # doctest: +SKIP
>>> plt.title('inverse of stats.pareto(5)')
rand(*args) method of numpy.random.mtrand.RandomState instance
rand(d0, d1, ..., dn)
Random values in a given shape.
.. note::
This is a convenience function for users porting code from Matlab,
and wraps `random_sample`. That function takes a
tuple to specify the size of the output, which is consistent with
other NumPy functions like `numpy.zeros` and `numpy.ones`.
Create an array of the given shape and populate it with
random samples from a uniform distribution
over ``[0, 1)``.
Parameters
----------
d0, d1, ..., dn : int, optional
The dimensions of the returned array, must be non-negative.
If no argument is given a single Python float is returned.
Returns
-------
out : ndarray, shape ``(d0, d1, ..., dn)``
Random values.
See Also
--------
random
Examples
--------
>>> np.random.rand(3,2)
array([[ 0.14022471, 0.96360618], #random
[ 0.37601032, 0.25528411], #random
[ 0.49313049, 0.94909878]]) #random
randint(low, high=None, size=None, dtype=<class 'int'>) method of numpy.random.mtrand.RandomState instance
randint(low, high=None, size=None, dtype=int)
Return random integers from `low` (inclusive) to `high` (exclusive).
Return random integers from the "discrete uniform" distribution of
the specified dtype in the "half-open" interval [`low`, `high`). If
`high` is None (the default), then results are from [0, `low`).
.. note::
New code should use the `~numpy.random.Generator.integers`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
low : int or array-like of ints
Lowest (signed) integers to be drawn from the distribution (unless
``high=None``, in which case this parameter is one above the
*highest* such integer).
high : int or array-like of ints, optional
If provided, one above the largest (signed) integer to be drawn
from the distribution (see above for behavior if ``high=None``).
If array-like, must contain integer values
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
dtype : dtype, optional
Desired dtype of the result. Byteorder must be native.
The default value is long.
.. versionadded:: 1.11.0
.. warning::
This function defaults to the C-long dtype, which is 32bit on windows
and otherwise 64bit on 64bit platforms (and 32bit on 32bit ones).
Since NumPy 2.0, NumPy's default integer is 32bit on 32bit platforms
and 64bit on 64bit platforms. Which corresponds to `np.intp`.
(`dtype=int` is not the same as in most NumPy functions.)
Returns
-------
out : int or ndarray of ints
`size`-shaped array of random integers from the appropriate
distribution, or a single such random int if `size` not provided.
See Also
--------
random_integers : similar to `randint`, only for the closed
interval [`low`, `high`], and 1 is the lowest value if `high` is
omitted.
random.Generator.integers: which should be used for new code.
Examples
--------
>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) # random
>>> np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Generate a 2 x 4 array of ints between 0 and 4, inclusive:
>>> np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1], # random
[3, 2, 2, 0]])
Generate a 1 x 3 array with 3 different upper bounds
>>> np.random.randint(1, [3, 5, 10])
array([2, 2, 9]) # random
Generate a 1 by 3 array with 3 different lower bounds
>>> np.random.randint([1, 5, 7], 10)
array([9, 8, 7]) # random
Generate a 2 by 4 array using broadcasting with dtype of uint8
>>> np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
array([[ 8, 6, 9, 7], # random
[ 1, 16, 9, 12]], dtype=uint8)
randn(*args) method of numpy.random.mtrand.RandomState instance
randn(d0, d1, ..., dn)
Return a sample (or samples) from the "standard normal" distribution.
.. note::
This is a convenience function for users porting code from Matlab,
and wraps `standard_normal`. That function takes a
tuple to specify the size of the output, which is consistent with
other NumPy functions like `numpy.zeros` and `numpy.ones`.
.. note::
New code should use the
`~numpy.random.Generator.standard_normal`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
If positive int_like arguments are provided, `randn` generates an array
of shape ``(d0, d1, ..., dn)``, filled
with random floats sampled from a univariate "normal" (Gaussian)
distribution of mean 0 and variance 1. A single float randomly sampled
from the distribution is returned if no argument is provided.
Parameters
----------
d0, d1, ..., dn : int, optional
The dimensions of the returned array, must be non-negative.
If no argument is given a single Python float is returned.
Returns
-------
Z : ndarray or float
A ``(d0, d1, ..., dn)``-shaped array of floating-point samples from
the standard normal distribution, or a single such float if
no parameters were supplied.
See Also
--------
standard_normal : Similar, but takes a tuple as its argument.
normal : Also accepts mu and sigma arguments.
random.Generator.standard_normal: which should be used for new code.
Notes
-----
For random samples from the normal distribution with mean ``mu`` and
standard deviation ``sigma``, use::
sigma * np.random.randn(...) + mu
Examples
--------
>>> np.random.randn()
2.1923875335537315 # random
Two-by-four array of samples from the normal distribution with
mean 3 and standard deviation 2.5:
>>> 3 + 2.5 * np.random.randn(2, 4)
array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random
[ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random
random(size=None) method of numpy.random.mtrand.RandomState instance
random(size=None)
Return random floats in the half-open interval [0.0, 1.0). Alias for
`random_sample` to ease forward-porting to the new random API.
random_integers(low, high=None, size=None) method of numpy.random.mtrand.RandomState instance
random_integers(low, high=None, size=None)
Random integers of type `numpy.int_` between `low` and `high`, inclusive.
Return random integers of type `numpy.int_` from the "discrete uniform"
distribution in the closed interval [`low`, `high`]. If `high` is
None (the default), then results are from [1, `low`]. The `numpy.int_`
type translates to the C long integer type and its precision
is platform dependent.
This function has been deprecated. Use randint instead.
.. deprecated:: 1.11.0
Parameters
----------
low : int
Lowest (signed) integer to be drawn from the distribution (unless
``high=None``, in which case this parameter is the *highest* such
integer).
high : int, optional
If provided, the largest (signed) integer to be drawn from the
distribution (see above for behavior if ``high=None``).
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
Returns
-------
out : int or ndarray of ints
`size`-shaped array of random integers from the appropriate
distribution, or a single such random int if `size` not provided.
See Also
--------
randint : Similar to `random_integers`, only for the half-open
interval [`low`, `high`), and 0 is the lowest value if `high` is
omitted.
Notes
-----
To sample from N evenly spaced floating-point numbers between a and b,
use::
a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.)
Examples
--------
>>> np.random.random_integers(5)
4 # random
>>> type(np.random.random_integers(5))
<class 'numpy.int64'>
>>> np.random.random_integers(5, size=(3,2))
array([[5, 4], # random
[3, 3],
[4, 5]])
Choose five random numbers from the set of five evenly-spaced
numbers between 0 and 2.5, inclusive (*i.e.*, from the set
:math:`{0, 5/8, 10/8, 15/8, 20/8}`):
>>> 2.5 * (np.random.random_integers(5, size=(5,)) - 1) / 4.
array([ 0.625, 1.25 , 0.625, 0.625, 2.5 ]) # random
Roll two six sided dice 1000 times and sum the results:
>>> d1 = np.random.random_integers(1, 6, 1000)
>>> d2 = np.random.random_integers(1, 6, 1000)
>>> dsums = d1 + d2
Display results as a histogram:
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(dsums, 11, density=True)
>>> plt.show()
random_sample(size=None) method of numpy.random.mtrand.RandomState instance
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
Results are from the "continuous uniform" distribution over the
stated interval. To sample :math:`Unif[a, b), b > a` multiply
the output of `random_sample` by `(b-a)` and add `a`::
(b - a) * random_sample() + a
.. note::
New code should use the `~numpy.random.Generator.random`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
Returns
-------
out : float or ndarray of floats
Array of random floats of shape `size` (unless ``size=None``, in which
case a single float is returned).
See Also
--------
random.Generator.random: which should be used for new code.
Examples
--------
>>> np.random.random_sample()
0.47108547995356098 # random
>>> type(np.random.random_sample())
<class 'float'>
>>> np.random.random_sample((5,))
array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428]) # random
Three-by-two array of random numbers from [-5, 0):
>>> 5 * np.random.random_sample((3, 2)) - 5
array([[-3.99149989, -0.52338984], # random
[-2.99091858, -0.79479508],
[-1.23204345, -1.75224494]])
ranf(*args, **kwargs)
This is an alias of `random_sample`. See `random_sample` for the complete
documentation.
rayleigh(scale=1.0, size=None) method of numpy.random.mtrand.RandomState instance
rayleigh(scale=1.0, size=None)
Draw samples from a Rayleigh distribution.
The :math:`\chi` and Weibull distributions are generalizations of the
Rayleigh.
.. note::
New code should use the `~numpy.random.Generator.rayleigh`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
scale : float or array_like of floats, optional
Scale, also equals the mode. Must be non-negative. Default is 1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``scale`` is a scalar. Otherwise,
``np.array(scale).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized Rayleigh distribution.
See Also
--------
random.Generator.rayleigh: which should be used for new code.
Notes
-----
The probability density function for the Rayleigh distribution is
.. math:: P(x;scale) = \frac{x}{scale^2}e^{\frac{-x^2}{2 \cdotp scale^2}}
The Rayleigh distribution would arise, for example, if the East
and North components of the wind velocity had identical zero-mean
Gaussian distributions. Then the wind speed would have a Rayleigh
distribution.
References
----------
.. [1] Brighton Webs Ltd., "Rayleigh Distribution,"
https://web.archive.org/web/20090514091424/http://brighton-webs.co.uk:80/distributions/rayleigh.asp
.. [2] Wikipedia, "Rayleigh distribution"
https://en.wikipedia.org/wiki/Rayleigh_distribution
Examples
--------
Draw values from the distribution and plot the histogram
>>> from matplotlib.pyplot import hist
>>> values = hist(np.random.rayleigh(3, 100000), bins=200, density=True)
Wave heights tend to follow a Rayleigh distribution. If the mean wave
height is 1 meter, what fraction of waves are likely to be larger than 3
meters?
>>> meanvalue = 1
>>> modevalue = np.sqrt(2 / np.pi) * meanvalue
>>> s = np.random.rayleigh(modevalue, 1000000)
The percentage of waves larger than 3 meters is:
>>> 100.*sum(s>3)/1000000.
0.087300000000000003 # random
sample(*args, **kwargs)
This is an alias of `random_sample`. See `random_sample` for the complete
documentation.
seed(seed=None)
seed(seed=None)
Reseed the singleton RandomState instance.
Notes
-----
This is a convenience, legacy function that exists to support
older code that uses the singleton RandomState. Best practice
is to use a dedicated ``Generator`` instance rather than
the random variate generation methods exposed directly in
the random module.
See Also
--------
numpy.random.Generator
set_state(state) method of numpy.random.mtrand.RandomState instance
set_state(state)
Set the internal state of the generator from a tuple.
For use if one has reason to manually (re-)set the internal state of
the bit generator used by the RandomState instance. By default,
RandomState uses the "Mersenne Twister"[1]_ pseudo-random number
generating algorithm.
Parameters
----------
state : {tuple(str, ndarray of 624 uints, int, int, float), dict}
The `state` tuple has the following items:
1. the string 'MT19937', specifying the Mersenne Twister algorithm.
2. a 1-D array of 624 unsigned integers ``keys``.
3. an integer ``pos``.
4. an integer ``has_gauss``.
5. a float ``cached_gaussian``.
If state is a dictionary, it is directly set using the BitGenerators
`state` property.
Returns
-------
out : None
Returns 'None' on success.
See Also
--------
get_state
Notes
-----
`set_state` and `get_state` are not needed to work with any of the
random distributions in NumPy. If the internal state is manually altered,
the user should know exactly what he/she is doing.
For backwards compatibility, the form (str, array of 624 uints, int) is
also accepted although it is missing some information about the cached
Gaussian value: ``state = ('MT19937', keys, pos)``.
References
----------
.. [1] M. Matsumoto and T. Nishimura, "Mersenne Twister: A
623-dimensionally equidistributed uniform pseudorandom number
generator," *ACM Trans. on Modeling and Computer Simulation*,
Vol. 8, No. 1, pp. 3-30, Jan. 1998.
shuffle(x) method of numpy.random.mtrand.RandomState instance
shuffle(x)
Modify a sequence in-place by shuffling its contents.
This function only shuffles the array along the first axis of a
multi-dimensional array. The order of sub-arrays is changed but
their contents remains the same.
.. note::
New code should use the `~numpy.random.Generator.shuffle`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
x : ndarray or MutableSequence
The array, list or mutable sequence to be shuffled.
Returns
-------
None
See Also
--------
random.Generator.shuffle: which should be used for new code.
Examples
--------
>>> arr = np.arange(10)
>>> np.random.shuffle(arr)
>>> arr
[1 7 5 2 9 4 3 6 0 8] # random
Multi-dimensional arrays are only shuffled along the first axis:
>>> arr = np.arange(9).reshape((3, 3))
>>> np.random.shuffle(arr)
>>> arr
array([[3, 4, 5], # random
[6, 7, 8],
[0, 1, 2]])
standard_cauchy(size=None) method of numpy.random.mtrand.RandomState instance
standard_cauchy(size=None)
Draw samples from a standard Cauchy distribution with mode = 0.
Also known as the Lorentz distribution.
.. note::
New code should use the
`~numpy.random.Generator.standard_cauchy`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
Returns
-------
samples : ndarray or scalar
The drawn samples.
See Also
--------
random.Generator.standard_cauchy: which should be used for new code.
Notes
-----
The probability density function for the full Cauchy distribution is
.. math:: P(x; x_0, \gamma) = \frac{1}{\pi \gamma \bigl[ 1+
(\frac{x-x_0}{\gamma})^2 \bigr] }
and the Standard Cauchy distribution just sets :math:`x_0=0` and
:math:`\gamma=1`
The Cauchy distribution arises in the solution to the driven harmonic
oscillator problem, and also describes spectral line broadening. It
also describes the distribution of values at which a line tilted at
a random angle will cut the x axis.
When studying hypothesis tests that assume normality, seeing how the
tests perform on data from a Cauchy distribution is a good indicator of
their sensitivity to a heavy-tailed distribution, since the Cauchy looks
very much like a Gaussian distribution, but with heavier tails.
References
----------
.. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "Cauchy
Distribution",
https://www.itl.nist.gov/div898/handbook/eda/section3/eda3663.htm
.. [2] Weisstein, Eric W. "Cauchy Distribution." From MathWorld--A
Wolfram Web Resource.
https://mathworld.wolfram.com/CauchyDistribution.html
.. [3] Wikipedia, "Cauchy distribution"
https://en.wikipedia.org/wiki/Cauchy_distribution
Examples
--------
Draw samples and plot the distribution:
>>> import matplotlib.pyplot as plt
>>> s = np.random.standard_cauchy(1000000)
>>> s = s[(s>-25) & (s<25)] # truncate distribution so it plots well
>>> plt.hist(s, bins=100)
>>> plt.show()
standard_exponential(size=None) method of numpy.random.mtrand.RandomState instance
standard_exponential(size=None)
Draw samples from the standard exponential distribution.
`standard_exponential` is identical to the exponential distribution
with a scale parameter of 1.
.. note::
New code should use the
`~numpy.random.Generator.standard_exponential`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
Returns
-------
out : float or ndarray
Drawn samples.
See Also
--------
random.Generator.standard_exponential: which should be used for new code.
Examples
--------
Output a 3x8000 array:
>>> n = np.random.standard_exponential((3, 8000))
standard_gamma(shape, size=None) method of numpy.random.mtrand.RandomState instance
standard_gamma(shape, size=None)
Draw samples from a standard Gamma distribution.
Samples are drawn from a Gamma distribution with specified parameters,
shape (sometimes designated "k") and scale=1.
.. note::
New code should use the
`~numpy.random.Generator.standard_gamma`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
shape : float or array_like of floats
Parameter, must be non-negative.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``shape`` is a scalar. Otherwise,
``np.array(shape).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized standard gamma distribution.
See Also
--------
scipy.stats.gamma : probability density function, distribution or
cumulative density function, etc.
random.Generator.standard_gamma: which should be used for new code.
Notes
-----
The probability density for the Gamma distribution is
.. math:: p(x) = x^{k-1}\frac{e^{-x/\theta}}{\theta^k\Gamma(k)},
where :math:`k` is the shape and :math:`\theta` the scale,
and :math:`\Gamma` is the Gamma function.
The Gamma distribution is often used to model the times to failure of
electronic components, and arises naturally in processes for which the
waiting times between Poisson distributed events are relevant.
References
----------
.. [1] Weisstein, Eric W. "Gamma Distribution." From MathWorld--A
Wolfram Web Resource.
https://mathworld.wolfram.com/GammaDistribution.html
.. [2] Wikipedia, "Gamma distribution",
https://en.wikipedia.org/wiki/Gamma_distribution
Examples
--------
Draw samples from the distribution:
>>> shape, scale = 2., 1. # mean and width
>>> s = np.random.standard_gamma(shape, 1000000)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> import scipy.special as sps # doctest: +SKIP
>>> count, bins, ignored = plt.hist(s, 50, density=True)
>>> y = bins**(shape-1) * ((np.exp(-bins/scale))/ # doctest: +SKIP
... (sps.gamma(shape) * scale**shape))
>>> plt.plot(bins, y, linewidth=2, color='r') # doctest: +SKIP
>>> plt.show()
standard_normal(size=None) method of numpy.random.mtrand.RandomState instance
standard_normal(size=None)
Draw samples from a standard Normal distribution (mean=0, stdev=1).
.. note::
New code should use the
`~numpy.random.Generator.standard_normal`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. Default is None, in which case a
single value is returned.
Returns
-------
out : float or ndarray
A floating-point array of shape ``size`` of drawn samples, or a
single sample if ``size`` was not specified.
See Also
--------
normal :
Equivalent function with additional ``loc`` and ``scale`` arguments
for setting the mean and standard deviation.
random.Generator.standard_normal: which should be used for new code.
Notes
-----
For random samples from the normal distribution with mean ``mu`` and
standard deviation ``sigma``, use one of::
mu + sigma * np.random.standard_normal(size=...)
np.random.normal(mu, sigma, size=...)
Examples
--------
>>> np.random.standard_normal()
2.1923875335537315 #random
>>> s = np.random.standard_normal(8000)
>>> s
array([ 0.6888893 , 0.78096262, -0.89086505, ..., 0.49876311, # random
-0.38672696, -0.4685006 ]) # random
>>> s.shape
(8000,)
>>> s = np.random.standard_normal(size=(3, 4, 2))
>>> s.shape
(3, 4, 2)
Two-by-four array of samples from the normal distribution with
mean 3 and standard deviation 2.5:
>>> 3 + 2.5 * np.random.standard_normal(size=(2, 4))
array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], # random
[ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) # random
standard_t(df, size=None) method of numpy.random.mtrand.RandomState instance
standard_t(df, size=None)
Draw samples from a standard Student's t distribution with `df` degrees
of freedom.
A special case of the hyperbolic distribution. As `df` gets
large, the result resembles that of the standard normal
distribution (`standard_normal`).
.. note::
New code should use the `~numpy.random.Generator.standard_t`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
df : float or array_like of floats
Degrees of freedom, must be > 0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``df`` is a scalar. Otherwise,
``np.array(df).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized standard Student's t distribution.
See Also
--------
random.Generator.standard_t: which should be used for new code.
Notes
-----
The probability density function for the t distribution is
.. math:: P(x, df) = \frac{\Gamma(\frac{df+1}{2})}{\sqrt{\pi df}
\Gamma(\frac{df}{2})}\Bigl( 1+\frac{x^2}{df} \Bigr)^{-(df+1)/2}
The t test is based on an assumption that the data come from a
Normal distribution. The t test provides a way to test whether
the sample mean (that is the mean calculated from the data) is
a good estimate of the true mean.
The derivation of the t-distribution was first published in
1908 by William Gosset while working for the Guinness Brewery
in Dublin. Due to proprietary issues, he had to publish under
a pseudonym, and so he used the name Student.
References
----------
.. [1] Dalgaard, Peter, "Introductory Statistics With R",
Springer, 2002.
.. [2] Wikipedia, "Student's t-distribution"
https://en.wikipedia.org/wiki/Student's_t-distribution
Examples
--------
From Dalgaard page 83 [1]_, suppose the daily energy intake for 11
women in kilojoules (kJ) is:
>>> intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515, \
... 7515, 8230, 8770])
Does their energy intake deviate systematically from the recommended
value of 7725 kJ? Our null hypothesis will be the absence of deviation,
and the alternate hypothesis will be the presence of an effect that could be
either positive or negative, hence making our test 2-tailed.
Because we are estimating the mean and we have N=11 values in our sample,
we have N-1=10 degrees of freedom. We set our significance level to 95% and
compute the t statistic using the empirical mean and empirical standard
deviation of our intake. We use a ddof of 1 to base the computation of our
empirical standard deviation on an unbiased estimate of the variance (note:
the final estimate is not unbiased due to the concave nature of the square
root).
>>> np.mean(intake)
6753.636363636364
>>> intake.std(ddof=1)
1142.1232221373727
>>> t = (np.mean(intake)-7725)/(intake.std(ddof=1)/np.sqrt(len(intake)))
>>> t
-2.8207540608310198
We draw 1000000 samples from Student's t distribution with the adequate
degrees of freedom.
>>> import matplotlib.pyplot as plt
>>> s = np.random.standard_t(10, size=1000000)
>>> h = plt.hist(s, bins=100, density=True)
Does our t statistic land in one of the two critical regions found at
both tails of the distribution?
>>> np.sum(np.abs(t) < np.abs(s)) / float(len(s))
0.018318 #random < 0.05, statistic is in critical region
The probability value for this 2-tailed test is about 1.83%, which is
lower than the 5% pre-determined significance threshold.
Therefore, the probability of observing values as extreme as our intake
conditionally on the null hypothesis being true is too low, and we reject
the null hypothesis of no deviation.
triangular(left, mode, right, size=None) method of numpy.random.mtrand.RandomState instance
triangular(left, mode, right, size=None)
Draw samples from the triangular distribution over the
interval ``[left, right]``.
The triangular distribution is a continuous probability
distribution with lower limit left, peak at mode, and upper
limit right. Unlike the other distributions, these parameters
directly define the shape of the pdf.
.. note::
New code should use the `~numpy.random.Generator.triangular`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
left : float or array_like of floats
Lower limit.
mode : float or array_like of floats
The value where the peak of the distribution occurs.
The value must fulfill the condition ``left <= mode <= right``.
right : float or array_like of floats
Upper limit, must be larger than `left`.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``left``, ``mode``, and ``right``
are all scalars. Otherwise, ``np.broadcast(left, mode, right).size``
samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized triangular distribution.
See Also
--------
random.Generator.triangular: which should be used for new code.
Notes
-----
The probability density function for the triangular distribution is
.. math:: P(x;l, m, r) = \begin{cases}
\frac{2(x-l)}{(r-l)(m-l)}& \text{for $l \leq x \leq m$},\\
\frac{2(r-x)}{(r-l)(r-m)}& \text{for $m \leq x \leq r$},\\
0& \text{otherwise}.
\end{cases}
The triangular distribution is often used in ill-defined
problems where the underlying distribution is not known, but
some knowledge of the limits and mode exists. Often it is used
in simulations.
References
----------
.. [1] Wikipedia, "Triangular distribution"
https://en.wikipedia.org/wiki/Triangular_distribution
Examples
--------
Draw values from the distribution and plot the histogram:
>>> import matplotlib.pyplot as plt
>>> h = plt.hist(np.random.triangular(-3, 0, 8, 100000), bins=200,
... density=True)
>>> plt.show()
uniform(low=0.0, high=1.0, size=None) method of numpy.random.mtrand.RandomState instance
uniform(low=0.0, high=1.0, size=None)
Draw samples from a uniform distribution.
Samples are uniformly distributed over the half-open interval
``[low, high)`` (includes low, but excludes high). In other words,
any value within the given interval is equally likely to be drawn
by `uniform`.
.. note::
New code should use the `~numpy.random.Generator.uniform`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
low : float or array_like of floats, optional
Lower boundary of the output interval. All values generated will be
greater than or equal to low. The default value is 0.
high : float or array_like of floats
Upper boundary of the output interval. All values generated will be
less than or equal to high. The high limit may be included in the
returned array of floats due to floating-point rounding in the
equation ``low + (high-low) * random_sample()``. The default value
is 1.0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``low`` and ``high`` are both scalars.
Otherwise, ``np.broadcast(low, high).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized uniform distribution.
See Also
--------
randint : Discrete uniform distribution, yielding integers.
random_integers : Discrete uniform distribution over the closed
interval ``[low, high]``.
random_sample : Floats uniformly distributed over ``[0, 1)``.
random : Alias for `random_sample`.
rand : Convenience function that accepts dimensions as input, e.g.,
``rand(2,2)`` would generate a 2-by-2 array of floats,
uniformly distributed over ``[0, 1)``.
random.Generator.uniform: which should be used for new code.
Notes
-----
The probability density function of the uniform distribution is
.. math:: p(x) = \frac{1}{b - a}
anywhere within the interval ``[a, b)``, and zero elsewhere.
When ``high`` == ``low``, values of ``low`` will be returned.
If ``high`` < ``low``, the results are officially undefined
and may eventually raise an error, i.e. do not rely on this
function to behave when passed arguments satisfying that
inequality condition. The ``high`` limit may be included in the
returned array of floats due to floating-point rounding in the
equation ``low + (high-low) * random_sample()``. For example:
>>> x = np.float32(5*0.99999999)
>>> x
5.0
Examples
--------
Draw samples from the distribution:
>>> s = np.random.uniform(-1,0,1000)
All values are within the given interval:
>>> np.all(s >= -1)
True
>>> np.all(s < 0)
True
Display the histogram of the samples, along with the
probability density function:
>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 15, density=True)
>>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
>>> plt.show()
vonmises(mu, kappa, size=None) method of numpy.random.mtrand.RandomState instance
vonmises(mu, kappa, size=None)
Draw samples from a von Mises distribution.
Samples are drawn from a von Mises distribution with specified mode
(mu) and dispersion (kappa), on the interval [-pi, pi].
The von Mises distribution (also known as the circular normal
distribution) is a continuous probability distribution on the unit
circle. It may be thought of as the circular analogue of the normal
distribution.
.. note::
New code should use the `~numpy.random.Generator.vonmises`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
mu : float or array_like of floats
Mode ("center") of the distribution.
kappa : float or array_like of floats
Dispersion of the distribution, has to be >=0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``mu`` and ``kappa`` are both scalars.
Otherwise, ``np.broadcast(mu, kappa).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized von Mises distribution.
See Also
--------
scipy.stats.vonmises : probability density function, distribution, or
cumulative density function, etc.
random.Generator.vonmises: which should be used for new code.
Notes
-----
The probability density for the von Mises distribution is
.. math:: p(x) = \frac{e^{\kappa cos(x-\mu)}}{2\pi I_0(\kappa)},
where :math:`\mu` is the mode and :math:`\kappa` the dispersion,
and :math:`I_0(\kappa)` is the modified Bessel function of order 0.
The von Mises is named for Richard Edler von Mises, who was born in
Austria-Hungary, in what is now the Ukraine. He fled to the United
States in 1939 and became a professor at Harvard. He worked in
probability theory, aerodynamics, fluid mechanics, and philosophy of
science.
References
----------
.. [1] Abramowitz, M. and Stegun, I. A. (Eds.). "Handbook of
Mathematical Functions with Formulas, Graphs, and Mathematical
Tables, 9th printing," New York: Dover, 1972.
.. [2] von Mises, R., "Mathematical Theory of Probability
and Statistics", New York: Academic Press, 1964.
Examples
--------
Draw samples from the distribution:
>>> mu, kappa = 0.0, 4.0 # mean and dispersion
>>> s = np.random.vonmises(mu, kappa, 1000)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> from scipy.special import i0 # doctest: +SKIP
>>> plt.hist(s, 50, density=True)
>>> x = np.linspace(-np.pi, np.pi, num=51)
>>> y = np.exp(kappa*np.cos(x-mu))/(2*np.pi*i0(kappa)) # doctest: +SKIP
>>> plt.plot(x, y, linewidth=2, color='r') # doctest: +SKIP
>>> plt.show()
wald(mean, scale, size=None) method of numpy.random.mtrand.RandomState instance
wald(mean, scale, size=None)
Draw samples from a Wald, or inverse Gaussian, distribution.
As the scale approaches infinity, the distribution becomes more like a
Gaussian. Some references claim that the Wald is an inverse Gaussian
with mean equal to 1, but this is by no means universal.
The inverse Gaussian distribution was first studied in relationship to
Brownian motion. In 1956 M.C.K. Tweedie used the name inverse Gaussian
because there is an inverse relationship between the time to cover a
unit distance and distance covered in unit time.
.. note::
New code should use the `~numpy.random.Generator.wald`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
mean : float or array_like of floats
Distribution mean, must be > 0.
scale : float or array_like of floats
Scale parameter, must be > 0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``mean`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(mean, scale).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized Wald distribution.
See Also
--------
random.Generator.wald: which should be used for new code.
Notes
-----
The probability density function for the Wald distribution is
.. math:: P(x;mean,scale) = \sqrt{\frac{scale}{2\pi x^3}}e^
\frac{-scale(x-mean)^2}{2\cdotp mean^2x}
As noted above the inverse Gaussian distribution first arise
from attempts to model Brownian motion. It is also a
competitor to the Weibull for use in reliability modeling and
modeling stock returns and interest rate processes.
References
----------
.. [1] Brighton Webs Ltd., Wald Distribution,
https://web.archive.org/web/20090423014010/http://www.brighton-webs.co.uk:80/distributions/wald.asp
.. [2] Chhikara, Raj S., and Folks, J. Leroy, "The Inverse Gaussian
Distribution: Theory : Methodology, and Applications", CRC Press,
1988.
.. [3] Wikipedia, "Inverse Gaussian distribution"
https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution
Examples
--------
Draw values from the distribution and plot the histogram:
>>> import matplotlib.pyplot as plt
>>> h = plt.hist(np.random.wald(3, 2, 100000), bins=200, density=True)
>>> plt.show()
weibull(a, size=None) method of numpy.random.mtrand.RandomState instance
weibull(a, size=None)
Draw samples from a Weibull distribution.
Draw samples from a 1-parameter Weibull distribution with the given
shape parameter `a`.
.. math:: X = (-ln(U))^{1/a}
Here, U is drawn from the uniform distribution over (0,1].
The more common 2-parameter Weibull, including a scale parameter
:math:`\lambda` is just :math:`X = \lambda(-ln(U))^{1/a}`.
.. note::
New code should use the `~numpy.random.Generator.weibull`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
a : float or array_like of floats
Shape parameter of the distribution. Must be nonnegative.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``a`` is a scalar. Otherwise,
``np.array(a).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized Weibull distribution.
See Also
--------
scipy.stats.weibull_max
scipy.stats.weibull_min
scipy.stats.genextreme
gumbel
random.Generator.weibull: which should be used for new code.
Notes
-----
The Weibull (or Type III asymptotic extreme value distribution
for smallest values, SEV Type III, or Rosin-Rammler
distribution) is one of a class of Generalized Extreme Value
(GEV) distributions used in modeling extreme value problems.
This class includes the Gumbel and Frechet distributions.
The probability density for the Weibull distribution is
.. math:: p(x) = \frac{a}
{\lambda}(\frac{x}{\lambda})^{a-1}e^{-(x/\lambda)^a},
where :math:`a` is the shape and :math:`\lambda` the scale.
The function has its peak (the mode) at
:math:`\lambda(\frac{a-1}{a})^{1/a}`.
When ``a = 1``, the Weibull distribution reduces to the exponential
distribution.
References
----------
.. [1] Waloddi Weibull, Royal Technical University, Stockholm,
1939 "A Statistical Theory Of The Strength Of Materials",
Ingeniorsvetenskapsakademiens Handlingar Nr 151, 1939,
Generalstabens Litografiska Anstalts Forlag, Stockholm.
.. [2] Waloddi Weibull, "A Statistical Distribution Function of
Wide Applicability", Journal Of Applied Mechanics ASME Paper
1951.
.. [3] Wikipedia, "Weibull distribution",
https://en.wikipedia.org/wiki/Weibull_distribution
Examples
--------
Draw samples from the distribution:
>>> a = 5. # shape
>>> s = np.random.weibull(a, 1000)
Display the histogram of the samples, along with
the probability density function:
>>> import matplotlib.pyplot as plt
>>> x = np.arange(1,100.)/50.
>>> def weib(x,n,a):
... return (a / n) * (x / n)**(a - 1) * np.exp(-(x / n)**a)
>>> count, bins, ignored = plt.hist(np.random.weibull(5.,1000))
>>> x = np.arange(1,100.)/50.
>>> scale = count.max()/weib(x, 1., 5.).max()
>>> plt.plot(x, weib(x, 1., 5.)*scale)
>>> plt.show()
zipf(a, size=None) method of numpy.random.mtrand.RandomState instance
zipf(a, size=None)
Draw samples from a Zipf distribution.
Samples are drawn from a Zipf distribution with specified parameter
`a` > 1.
The Zipf distribution (also known as the zeta distribution) is a
discrete probability distribution that satisfies Zipf's law: the
frequency of an item is inversely proportional to its rank in a
frequency table.
.. note::
New code should use the `~numpy.random.Generator.zipf`
method of a `~numpy.random.Generator` instance instead;
please see the :ref:`random-quick-start`.
Parameters
----------
a : float or array_like of floats
Distribution parameter. Must be greater than 1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``a`` is a scalar. Otherwise,
``np.array(a).size`` samples are drawn.
Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized Zipf distribution.
See Also
--------
scipy.stats.zipf : probability density function, distribution, or
cumulative density function, etc.
random.Generator.zipf: which should be used for new code.
Notes
-----
The probability density for the Zipf distribution is
.. math:: p(k) = \frac{k^{-a}}{\zeta(a)},
for integers :math:`k \geq 1`, where :math:`\zeta` is the Riemann Zeta
function.
It is named for the American linguist George Kingsley Zipf, who noted
that the frequency of any word in a sample of a language is inversely
proportional to its rank in the frequency table.
References
----------
.. [1] Zipf, G. K., "Selected Studies of the Principle of Relative
Frequency in Language," Cambridge, MA: Harvard Univ. Press,
1932.
Examples
--------
Draw samples from the distribution:
>>> a = 4.0
>>> n = 20000
>>> s = np.random.zipf(a, n)
Display the histogram of the samples, along with
the expected histogram based on the probability
density function:
>>> import matplotlib.pyplot as plt
>>> from scipy.special import zeta # doctest: +SKIP
`bincount` provides a fast histogram for small integers.
>>> count = np.bincount(s)
>>> k = np.arange(1, s.max() + 1)
>>> plt.bar(k, count[1:], alpha=0.5, label='sample count')
>>> plt.plot(k, n*(k**-a)/zeta(a), 'k.-', alpha=0.5,
... label='expected count') # doctest: +SKIP
>>> plt.semilogy()
>>> plt.grid(alpha=0.4)
>>> plt.legend()
>>> plt.title(f'Zipf sample, a={a}, size={n}')
>>> plt.show()
DATA
__all__ = ['beta', 'binomial', 'bytes', 'chisquare', 'choice', 'dirich...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\random\__init__.py
numpy.ravel
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
ravel(a, order='C')
Return a contiguous flattened array.
A 1-D array, containing the elements of the input, is returned. A copy is
made only if needed.
As of NumPy 1.10, the returned array will have the same type as the input
array. (for example, a masked array will be returned for a masked array
input)
Parameters
----------
a : array_like
Input array. The elements in `a` are read in the order specified by
`order`, and packed as a 1-D array.
order : {'C','F', 'A', 'K'}, optional
The elements of `a` are read using this index order. 'C' means
to index the elements in row-major, C-style order,
with the last axis index changing fastest, back to the first
axis index changing slowest. 'F' means to index the elements
in column-major, Fortran-style order, with the
first index changing fastest, and the last index changing
slowest. Note that the 'C' and 'F' options take no account of
the memory layout of the underlying array, and only refer to
the order of axis indexing. 'A' means to read the elements in
Fortran-like index order if `a` is Fortran *contiguous* in
memory, C-like order otherwise. 'K' means to read the
elements in the order they occur in memory, except for
reversing the data when strides are negative. By default, 'C'
index order is used.
Returns
-------
y : array_like
y is a contiguous 1-D array of the same subtype as `a`,
with shape ``(a.size,)``.
Note that matrices are special cased for backward compatibility,
if `a` is a matrix, then y is a 1-D ndarray.
See Also
--------
ndarray.flat : 1-D iterator over an array.
ndarray.flatten : 1-D array copy of the elements of an array
in row-major order.
ndarray.reshape : Change the shape of an array without changing its data.
Notes
-----
In row-major, C-style order, in two dimensions, the row index
varies the slowest, and the column index the quickest. This can
be generalized to multiple dimensions, where row-major order
implies that the index along the first axis varies slowest, and
the index along the last quickest. The opposite holds for
column-major, Fortran-style index ordering.
When a view is desired in as many cases as possible, ``arr.reshape(-1)``
may be preferable. However, ``ravel`` supports ``K`` in the optional
``order`` argument while ``reshape`` does not.
Examples
--------
It is equivalent to ``reshape(-1, order=order)``.
>>> import numpy as np
>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.ravel(x)
array([1, 2, 3, 4, 5, 6])
>>> x.reshape(-1)
array([1, 2, 3, 4, 5, 6])
>>> np.ravel(x, order='F')
array([1, 4, 2, 5, 3, 6])
When ``order`` is 'A', it will preserve the array's 'C' or 'F' ordering:
>>> np.ravel(x.T)
array([1, 4, 2, 5, 3, 6])
>>> np.ravel(x.T, order='A')
array([1, 2, 3, 4, 5, 6])
When ``order`` is 'K', it will preserve orderings that are neither 'C'
nor 'F', but won't reverse axes:
>>> a = np.arange(3)[::-1]; a
array([2, 1, 0])
>>> a.ravel(order='C')
array([2, 1, 0])
>>> a.ravel(order='K')
array([2, 1, 0])
>>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a
array([[[ 0, 2, 4],
[ 1, 3, 5]],
[[ 6, 8, 10],
[ 7, 9, 11]]])
>>> a.ravel(order='C')
array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
>>> a.ravel(order='K')
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
numpy.ravel_multi_index
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
ravel_multi_index(...)
ravel_multi_index(multi_index, dims, mode='raise', order='C')
Converts a tuple of index arrays into an array of flat
indices, applying boundary modes to the multi-index.
Parameters
----------
multi_index : tuple of array_like
A tuple of integer arrays, one array for each dimension.
dims : tuple of ints
The shape of array into which the indices from ``multi_index`` apply.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices are handled. Can specify
either one mode or a tuple of modes, one mode per index.
* 'raise' -- raise an error (default)
* 'wrap' -- wrap around
* 'clip' -- clip to the range
In 'clip' mode, a negative index which would normally
wrap will clip to 0 instead.
order : {'C', 'F'}, optional
Determines whether the multi-index should be viewed as
indexing in row-major (C-style) or column-major
(Fortran-style) order.
Returns
-------
raveled_indices : ndarray
An array of indices into the flattened version of an array
of dimensions ``dims``.
See Also
--------
unravel_index
Notes
-----
.. versionadded:: 1.6.0
Examples
--------
>>> import numpy as np
>>> arr = np.array([[3,6,6],[4,5,1]])
>>> np.ravel_multi_index(arr, (7,6))
array([22, 41, 37])
>>> np.ravel_multi_index(arr, (7,6), order='F')
array([31, 41, 13])
>>> np.ravel_multi_index(arr, (4,6), mode='clip')
array([22, 23, 19])
>>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap'))
array([12, 13, 13])
>>> np.ravel_multi_index((3,1,4,1), (6,7,8,9))
1621
numpy.real
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
real(val)
Return the real part of the complex argument.
Parameters
----------
val : array_like
Input array.
Returns
-------
out : ndarray or scalar
The real component of the complex argument. If `val` is real, the type
of `val` is used for the output. If `val` has complex elements, the
returned type is float.
See Also
--------
real_if_close, imag, angle
Examples
--------
>>> import numpy as np
>>> a = np.array([1+2j, 3+4j, 5+6j])
>>> a.real
array([1., 3., 5.])
>>> a.real = 9
>>> a
array([9.+2.j, 9.+4.j, 9.+6.j])
>>> a.real = np.array([9, 8, 7])
>>> a
array([9.+2.j, 8.+4.j, 7.+6.j])
>>> np.real(1 + 1j)
1.0
numpy.real_if_close
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
real_if_close(a, tol=100)
If input is complex with all imaginary parts close to zero, return
real parts.
"Close to zero" is defined as `tol` * (machine epsilon of the type for
`a`).
Parameters
----------
a : array_like
Input array.
tol : float
Tolerance in machine epsilons for the complex part of the elements
in the array. If the tolerance is <=1, then the absolute tolerance
is used.
Returns
-------
out : ndarray
If `a` is real, the type of `a` is used for the output. If `a`
has complex elements, the returned type is float.
See Also
--------
real, imag, angle
Notes
-----
Machine epsilon varies from machine to machine and between data types
but Python floats on most platforms have a machine epsilon equal to
2.2204460492503131e-16. You can use 'np.finfo(float).eps' to print
out the machine epsilon for floats.
Examples
--------
>>> import numpy as np
>>> np.finfo(float).eps
2.2204460492503131e-16 # may vary
>>> np.real_if_close([2.1 + 4e-14j, 5.2 + 3e-15j], tol=1000)
array([2.1, 5.2])
>>> np.real_if_close([2.1 + 4e-13j, 5.2 + 3e-15j], tol=1000)
array([2.1+4.e-13j, 5.2 + 3e-15j])
numpy.rec
Python Library Documentation: package numpy.rec in numpy
NAME
numpy.rec - This module contains a set of functions for record arrays.
PACKAGE CONTENTS
CLASSES
builtins.object
format_parser
numpy.ndarray(builtins.object)
recarray
numpy.void(numpy.flexible)
numpy.record
class format_parser(builtins.object)
| format_parser(formats, names, titles, aligned=False, byteorder=None)
|
| Class to convert formats, names, titles description to a dtype.
|
| After constructing the format_parser object, the dtype attribute is
| the converted data-type:
| ``dtype = format_parser(formats, names, titles).dtype``
|
| Attributes
| ----------
| dtype : dtype
| The converted data-type.
|
| Parameters
| ----------
| formats : str or list of str
| The format description, either specified as a string with
| comma-separated format descriptions in the form ``'f8, i4, S5'``, or
| a list of format description strings in the form
| ``['f8', 'i4', 'S5']``.
| names : str or list/tuple of str
| The field names, either specified as a comma-separated string in the
| form ``'col1, col2, col3'``, or as a list or tuple of strings in the
| form ``['col1', 'col2', 'col3']``.
| An empty list can be used, in that case default field names
| ('f0', 'f1', ...) are used.
| titles : sequence
| Sequence of title strings. An empty list can be used to leave titles
| out.
| aligned : bool, optional
| If True, align the fields by padding as the C-compiler would.
| Default is False.
| byteorder : str, optional
| If specified, all the fields will be changed to the
| provided byte-order. Otherwise, the default byte-order is
| used. For all available string specifiers, see `dtype.newbyteorder`.
|
| See Also
| --------
| numpy.dtype, numpy.typename
|
| Examples
| --------
| >>> import numpy as np
| >>> np.rec.format_parser(['<f8', '<i4'], ['col1', 'col2'],
| ... ['T1', 'T2']).dtype
| dtype([(('T1', 'col1'), '<f8'), (('T2', 'col2'), '<i4')])
|
| `names` and/or `titles` can be empty lists. If `titles` is an empty list,
| titles will simply not appear. If `names` is empty, default field names
| will be used.
|
| >>> np.rec.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
| ... []).dtype
| dtype([('col1', '<f8'), ('col2', '<i4'), ('col3', '<S5')])
| >>> np.rec.format_parser(['<f8', '<i4', '<a5'], [], []).dtype
| dtype([('f0', '<f8'), ('f1', '<i4'), ('f2', 'S5')])
|
| Methods defined here:
|
| __init__(self, formats, names, titles, aligned=False, byteorder=None) from numpy._core.records.format_parser
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class recarray(numpy.ndarray)
| recarray(shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, order='C')
|
| Construct an ndarray that allows field access using attributes.
|
| Arrays may have a data-types containing fields, analogous
| to columns in a spread sheet. An example is ``[(x, int), (y, float)]``,
| where each entry in the array is a pair of ``(int, float)``. Normally,
| these attributes are accessed using dictionary lookups such as ``arr['x']``
| and ``arr['y']``. Record arrays allow the fields to be accessed as members
| of the array, using ``arr.x`` and ``arr.y``.
|
| Parameters
| ----------
| shape : tuple
| Shape of output array.
| dtype : data-type, optional
| The desired data-type. By default, the data-type is determined
| from `formats`, `names`, `titles`, `aligned` and `byteorder`.
| formats : list of data-types, optional
| A list containing the data-types for the different columns, e.g.
| ``['i4', 'f8', 'i4']``. `formats` does *not* support the new
| convention of using types directly, i.e. ``(int, float, int)``.
| Note that `formats` must be a list, not a tuple.
| Given that `formats` is somewhat limited, we recommend specifying
| `dtype` instead.
| names : tuple of str, optional
| The name of each column, e.g. ``('x', 'y', 'z')``.
| buf : buffer, optional
| By default, a new array is created of the given shape and data-type.
| If `buf` is specified and is an object exposing the buffer interface,
| the array will use the memory from the existing buffer. In this case,
| the `offset` and `strides` keywords are available.
|
| Other Parameters
| ----------------
| titles : tuple of str, optional
| Aliases for column names. For example, if `names` were
| ``('x', 'y', 'z')`` and `titles` is
| ``('x_coordinate', 'y_coordinate', 'z_coordinate')``, then
| ``arr['x']`` is equivalent to both ``arr.x`` and ``arr.x_coordinate``.
| byteorder : {'<', '>', '='}, optional
| Byte-order for all fields.
| aligned : bool, optional
| Align the fields in memory as the C-compiler would.
| strides : tuple of ints, optional
| Buffer (`buf`) is interpreted according to these strides (strides
| define how many bytes each array element, row, column, etc.
| occupy in memory).
| offset : int, optional
| Start reading buffer (`buf`) from this offset onwards.
| order : {'C', 'F'}, optional
| Row-major (C-style) or column-major (Fortran-style) order.
|
| Returns
| -------
| rec : recarray
| Empty array of the given shape and type.
|
| See Also
| --------
| numpy.rec.fromrecords : Construct a record array from data.
| numpy.record : fundamental data-type for `recarray`.
| numpy.rec.format_parser : determine data-type from formats, names, titles.
|
| Notes
| -----
| This constructor can be compared to ``empty``: it creates a new record
| array but does not fill it with data. To create a record array from data,
| use one of the following methods:
|
| 1. Create a standard ndarray and convert it to a record array,
| using ``arr.view(np.recarray)``
| 2. Use the `buf` keyword.
| 3. Use `np.rec.fromrecords`.
|
| Examples
| --------
| Create an array with two fields, ``x`` and ``y``:
|
| >>> import numpy as np
| >>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', '<f8'), ('y', '<i8')])
| >>> x
| array([(1., 2), (3., 4)], dtype=[('x', '<f8'), ('y', '<i8')])
|
| >>> x['x']
| array([1., 3.])
|
| View the array as a record array:
|
| >>> x = x.view(np.recarray)
|
| >>> x.x
| array([1., 3.])
|
| >>> x.y
| array([2, 4])
|
| Create a new, empty record array:
|
| >>> np.recarray((2,),
| ... dtype=[('x', int), ('y', float), ('z', int)]) #doctest: +SKIP
| rec.array([(-1073741821, 1.2249118382103472e-301, 24547520),
| (3471280, 1.2134086255804012e-316, 0)],
| dtype=[('x', '<i4'), ('y', '<f8'), ('z', '<i4')])
|
| Method resolution order:
| recarray
| numpy.ndarray
| builtins.object
|
| Methods defined here:
|
| __array_finalize__(self, obj) from numpy._core.records.recarray
| a.__array_finalize__(obj, /)
|
| Present so subclasses can call super. Does nothing.
|
| __getattribute__(self, attr) from numpy._core.records.recarray
| Return getattr(self, name).
|
| __getitem__(self, indx) from numpy._core.records.recarray
| Return self[key].
|
| __repr__(self) from numpy._core.records.recarray
| Return repr(self).
|
| __setattr__(self, attr, val) from numpy._core.records.recarray
| Implement setattr(self, name, value).
|
| field(self, attr, val=None) from numpy._core.records.recarray
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(subtype, shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, order='C') from numpy._core.records.recarray
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.ndarray:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| a.__array__([dtype], *, copy=None)
|
| For ``dtype`` parameter it returns a new reference to self if
| ``dtype`` is not given or it matches array's data type.
| A new array of provided data type is returned if ``dtype``
| is different from the current data type of the array.
| For ``copy`` parameter it returns a new reference to self if
| ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| parameter. The method returns a new array for ``copy=True``, regardless of
| ``dtype`` parameter.
|
| A more detailed explanation of the ``__array__`` interface
| can be found in :ref:`dunder_array.interface`.
|
| __array_function__(...)
|
| __array_namespace__(...)
|
| __array_ufunc__(...)
|
| __array_wrap__(...)
| a.__array_wrap__(array[, context], /)
|
| Returns a view of `array` with the same type as self.
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __complex__(...)
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __copy__(...)
| a.__copy__()
|
| Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
|
| Equivalent to ``a.copy(order='K')``.
|
| __deepcopy__(...)
| a.__deepcopy__(memo, /)
|
| Used if :func:`copy.deepcopy` is called on an array.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __dlpack__(...)
| a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
|
| DLPack Protocol: Part of the Array API.
|
| __dlpack_device__(...)
| a.__dlpack_device__()
|
| DLPack Protocol: Part of the Array API.
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Return self+=value.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __ifloordiv__(self, value, /)
| Return self//=value.
|
| __ilshift__(self, value, /)
| Return self<<=value.
|
| __imatmul__(self, value, /)
| Return self@=value.
|
| __imod__(self, value, /)
| Return self%=value.
|
| __imul__(self, value, /)
| Return self*=value.
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __ior__(self, value, /)
| Return self|=value.
|
| __ipow__(self, value, /)
| Return self**=value.
|
| __irshift__(self, value, /)
| Return self>>=value.
|
| __isub__(self, value, /)
| Return self-=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __itruediv__(self, value, /)
| Return self/=value.
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __matmul__(self, value, /)
| Return self@value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| a.__reduce__()
|
| For pickling.
|
| __reduce_ex__(...)
| Helper for pickle.
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmatmul__(self, value, /)
| Return value@self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __setstate__(...)
| a.__setstate__(state, /)
|
| For unpickling.
|
| The `state` argument must be a sequence that contains the following
| elements:
|
| Parameters
| ----------
| version : int
| optional pickle version. If omitted defaults to 0.
| shape : tuple
| dtype : data-type
| isFortran : bool
| rawdata : string or list
| a binary string with the data (or a list if 'a' is an object array)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| a.all(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if all elements evaluate to True.
|
| Refer to `numpy.all` for full documentation.
|
| See Also
| --------
| numpy.all : equivalent function
|
| any(...)
| a.any(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if any of the elements of `a` evaluate to True.
|
| Refer to `numpy.any` for full documentation.
|
| See Also
| --------
| numpy.any : equivalent function
|
| argmax(...)
| a.argmax(axis=None, out=None, *, keepdims=False)
|
| Return indices of the maximum values along the given axis.
|
| Refer to `numpy.argmax` for full documentation.
|
| See Also
| --------
| numpy.argmax : equivalent function
|
| argmin(...)
| a.argmin(axis=None, out=None, *, keepdims=False)
|
| Return indices of the minimum values along the given axis.
|
| Refer to `numpy.argmin` for detailed documentation.
|
| See Also
| --------
| numpy.argmin : equivalent function
|
| argpartition(...)
| a.argpartition(kth, axis=-1, kind='introselect', order=None)
|
| Returns the indices that would partition this array.
|
| Refer to `numpy.argpartition` for full documentation.
|
| .. versionadded:: 1.8.0
|
| See Also
| --------
| numpy.argpartition : equivalent function
|
| argsort(...)
| a.argsort(axis=-1, kind=None, order=None)
|
| Returns the indices that would sort this array.
|
| Refer to `numpy.argsort` for full documentation.
|
| See Also
| --------
| numpy.argsort : equivalent function
|
| astype(...)
| a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
|
| Copy of the array, cast to a specified type.
|
| Parameters
| ----------
| dtype : str or dtype
| Typecode or data-type to which the array is cast.
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout order of the result.
| '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.
| Default is 'K'.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'unsafe'
| for backwards compatibility.
|
| * '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.
| subok : bool, optional
| If True, then sub-classes will be passed-through (default), otherwise
| the returned array will be forced to be a base-class array.
| copy : bool, optional
| By default, astype always returns a newly allocated array. If this
| is set to false, and the `dtype`, `order`, and `subok`
| requirements are satisfied, the input array is returned instead
| of a copy.
|
| Returns
| -------
| arr_t : ndarray
| Unless `copy` is False and the other conditions for returning the input
| array are satisfied (see description for `copy` input parameter), `arr_t`
| is a new array of the same shape as the input array, with dtype, order
| given by `dtype`, `order`.
|
| Notes
| -----
| .. versionchanged:: 1.17.0
| Casting between a simple data type and a structured one is possible only
| for "unsafe" casting. Casting to multiple fields is allowed, but
| casting from multiple fields is not.
|
| .. versionchanged:: 1.9.0
| Casting from numeric to string types in 'safe' casting mode requires
| that the string dtype length is long enough to store the max
| integer/float value converted.
|
| Raises
| ------
| ComplexWarning
| When casting from complex to float or int. To avoid this,
| one should use ``a.real.astype(t)``.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 2.5])
| >>> x
| array([1. , 2. , 2.5])
|
| >>> x.astype(int)
| array([1, 2, 2])
|
| byteswap(...)
| a.byteswap(inplace=False)
|
| Swap the bytes of the array elements
|
| Toggle between low-endian and big-endian data representation by
| returning a byteswapped array, optionally swapped in-place.
| Arrays of byte-strings are not swapped. The real and imaginary
| parts of a complex number are swapped individually.
|
| Parameters
| ----------
| inplace : bool, optional
| If ``True``, swap bytes in-place, default is ``False``.
|
| Returns
| -------
| out : ndarray
| The byteswapped array. If `inplace` is ``True``, this is
| a view to self.
|
| Examples
| --------
| >>> import numpy as np
| >>> A = np.array([1, 256, 8755], dtype=np.int16)
| >>> list(map(hex, A))
| ['0x1', '0x100', '0x2233']
| >>> A.byteswap(inplace=True)
| array([ 256, 1, 13090], dtype=int16)
| >>> list(map(hex, A))
| ['0x100', '0x1', '0x3322']
|
| Arrays of byte-strings are not swapped
|
| >>> A = np.array([b'ceg', b'fac'])
| >>> A.byteswap()
| array([b'ceg', b'fac'], dtype='|S3')
|
| ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| the same values but different representation in memory
|
| >>> A = np.array([1, 2, 3])
| >>> A.view(np.uint8)
| array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| 0, 0], dtype=uint8)
| >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| array([1, 2, 3])
| >>> A.view(np.uint8)
| array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| 0, 3], dtype=uint8)
|
| choose(...)
| a.choose(choices, out=None, mode='raise')
|
| Use an index array to construct a new array from a set of choices.
|
| Refer to `numpy.choose` for full documentation.
|
| See Also
| --------
| numpy.choose : equivalent function
|
| clip(...)
| a.clip(min=None, max=None, out=None, **kwargs)
|
| Return an array whose values are limited to ``[min, max]``.
| One of max or min must be given.
|
| Refer to `numpy.clip` for full documentation.
|
| See Also
| --------
| numpy.clip : equivalent function
|
| compress(...)
| a.compress(condition, axis=None, out=None)
|
| Return selected slices of this array along given axis.
|
| Refer to `numpy.compress` for full documentation.
|
| See Also
| --------
| numpy.compress : equivalent function
|
| conj(...)
| a.conj()
|
| Complex-conjugate all elements.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| conjugate(...)
| a.conjugate()
|
| Return the complex conjugate, element-wise.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| copy(...)
| a.copy(order='C')
|
| Return a copy of the array.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout of the copy. 'C' means C-order,
| 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| 'C' otherwise. 'K' means match the layout of `a` as closely
| as possible. (Note that this function and :func:`numpy.copy` are very
| similar but have different default values for their order=
| arguments, and this function always passes sub-classes through.)
|
| See also
| --------
| numpy.copy : Similar function with different default behavior
| numpy.copyto
|
| Notes
| -----
| This function is the preferred method for creating an array copy. The
| function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| and will not pass sub-classes through by default.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[1,2,3],[4,5,6]], order='F')
|
| >>> y = x.copy()
|
| >>> x.fill(0)
|
| >>> x
| array([[0, 0, 0],
| [0, 0, 0]])
|
| >>> y
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> y.flags['C_CONTIGUOUS']
| True
|
| For arrays containing Python objects (e.g. dtype=object),
| the copy is a shallow one. The new array will contain the
| same object which may lead to surprises if that object can
| be modified (is mutable):
|
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> b = a.copy()
| >>> b[2][0] = 10
| >>> a
| array([1, 'm', list([10, 3, 4])], dtype=object)
|
| To ensure all elements within an ``object`` array are copied,
| use `copy.deepcopy`:
|
| >>> import copy
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> c = copy.deepcopy(a)
| >>> c[2][0] = 10
| >>> c
| array([1, 'm', list([10, 3, 4])], dtype=object)
| >>> a
| array([1, 'm', list([2, 3, 4])], dtype=object)
|
| cumprod(...)
| a.cumprod(axis=None, dtype=None, out=None)
|
| Return the cumulative product of the elements along the given axis.
|
| Refer to `numpy.cumprod` for full documentation.
|
| See Also
| --------
| numpy.cumprod : equivalent function
|
| cumsum(...)
| a.cumsum(axis=None, dtype=None, out=None)
|
| Return the cumulative sum of the elements along the given axis.
|
| Refer to `numpy.cumsum` for full documentation.
|
| See Also
| --------
| numpy.cumsum : equivalent function
|
| diagonal(...)
| a.diagonal(offset=0, axis1=0, axis2=1)
|
| Return specified diagonals. In NumPy 1.9 the returned array is a
| read-only view instead of a copy as in previous NumPy versions. In
| a future version the read-only restriction will be removed.
|
| Refer to :func:`numpy.diagonal` for full documentation.
|
| See Also
| --------
| numpy.diagonal : equivalent function
|
| dot(...)
|
| dump(...)
| a.dump(file)
|
| Dump a pickle of the array to the specified file.
| The array can be read back with pickle.load or numpy.load.
|
| Parameters
| ----------
| file : str or Path
| A string naming the dump file.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| dumps(...)
| a.dumps()
|
| Returns the pickle of the array as a string.
| pickle.loads will convert the string back to an array.
|
| Parameters
| ----------
| None
|
| fill(...)
| a.fill(value)
|
| Fill the array with a scalar value.
|
| Parameters
| ----------
| value : scalar
| All elements of `a` will be assigned this value.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([1, 2])
| >>> a.fill(0)
| >>> a
| array([0, 0])
| >>> a = np.empty(2)
| >>> a.fill(1)
| >>> a
| array([1., 1.])
|
| Fill expects a scalar value and always behaves the same as assigning
| to a single array element. The following is a rare example where this
| distinction is important:
|
| >>> a = np.array([None, None], dtype=object)
| >>> a[0] = np.array(3)
| >>> a
| array([array(3), None], dtype=object)
| >>> a.fill(np.array(3))
| >>> a
| array([array(3), array(3)], dtype=object)
|
| Where other forms of assignments will unpack the array being assigned:
|
| >>> a[...] = np.array(3)
| >>> a
| array([3, 3], dtype=object)
|
| flatten(...)
| a.flatten(order='C')
|
| Return a copy of the array collapsed into one dimension.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| 'C' means to flatten in row-major (C-style) order.
| 'F' means to flatten in column-major (Fortran-
| style) order. 'A' means to flatten in column-major
| order if `a` is Fortran *contiguous* in memory,
| row-major order otherwise. 'K' means to flatten
| `a` in the order the elements occur in memory.
| The default is 'C'.
|
| Returns
| -------
| y : ndarray
| A copy of the input array, flattened to one dimension.
|
| See Also
| --------
| ravel : Return a flattened array.
| flat : A 1-D flat iterator over the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,2], [3,4]])
| >>> a.flatten()
| array([1, 2, 3, 4])
| >>> a.flatten('F')
| array([1, 3, 2, 4])
|
| getfield(...)
| a.getfield(dtype, offset=0)
|
| Returns a field of the given array as a certain type.
|
| A field is a view of the array data with a given data-type. The values in
| the view are determined by the given type and the offset into the current
| array in bytes. The offset needs to be such that the view dtype fits in the
| array dtype; for example an array of dtype complex128 has 16-byte elements.
| If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| between 0 and 12 bytes.
|
| Parameters
| ----------
| dtype : str or dtype
| The data type of the view. The dtype size of the view can not be larger
| than that of the array itself.
| offset : int
| Number of bytes to skip before beginning the element view.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.diag([1.+1.j]*2)
| >>> x[1, 1] = 2 + 4.j
| >>> x
| array([[1.+1.j, 0.+0.j],
| [0.+0.j, 2.+4.j]])
| >>> x.getfield(np.float64)
| array([[1., 0.],
| [0., 2.]])
|
| By choosing an offset of 8 bytes we can select the complex part of the
| array for our view:
|
| >>> x.getfield(np.float64, offset=8)
| array([[1., 0.],
| [0., 4.]])
|
| item(...)
| a.item(*args)
|
| Copy an element of an array to a standard Python scalar and return it.
|
| Parameters
| ----------
| \*args : Arguments (variable number and type)
|
| * none: in this case, the method only works for arrays
| with one element (`a.size == 1`), which element is
| copied into a standard Python scalar object and returned.
|
| * int_type: this argument is interpreted as a flat index into
| the array, specifying which element to copy and return.
|
| * tuple of int_types: functions as does a single int_type argument,
| except that the argument is interpreted as an nd-index into the
| array.
|
| Returns
| -------
| z : Standard Python scalar object
| A copy of the specified element of the array as a suitable
| Python scalar
|
| Notes
| -----
| When the data type of `a` is longdouble or clongdouble, item() returns
| a scalar array object because there is no available Python scalar that
| would not lose information. Void arrays return a buffer object for item(),
| unless fields are defined, in which case a tuple is returned.
|
| `item` is very similar to a[args], except, instead of an array scalar,
| a standard Python scalar is returned. This can be useful for speeding up
| access to elements of the array and doing arithmetic on elements of the
| array using Python's optimized math.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.random.seed(123)
| >>> x = np.random.randint(9, size=(3, 3))
| >>> x
| array([[2, 2, 6],
| [1, 3, 6],
| [1, 0, 1]])
| >>> x.item(3)
| 1
| >>> x.item(7)
| 0
| >>> x.item((0, 1))
| 2
| >>> x.item((2, 2))
| 1
|
| For an array with object dtype, elements are returned as-is.
|
| >>> a = np.array([np.int64(1)], dtype=object)
| >>> a.item() #return np.int64
| np.int64(1)
|
| max(...)
| a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the maximum along a given axis.
|
| Refer to `numpy.amax` for full documentation.
|
| See Also
| --------
| numpy.amax : equivalent function
|
| mean(...)
| a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
|
| Returns the average of the array elements along given axis.
|
| Refer to `numpy.mean` for full documentation.
|
| See Also
| --------
| numpy.mean : equivalent function
|
| min(...)
| a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the minimum along a given axis.
|
| Refer to `numpy.amin` for full documentation.
|
| See Also
| --------
| numpy.amin : equivalent function
|
| nonzero(...)
| a.nonzero()
|
| Return the indices of the elements that are non-zero.
|
| Refer to `numpy.nonzero` for full documentation.
|
| See Also
| --------
| numpy.nonzero : equivalent function
|
| partition(...)
| a.partition(kth, axis=-1, kind='introselect', order=None)
|
| Partially sorts the elements in the array 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. In the output array, all elements smaller than the k-th element
| are located to the left of this element and all equal or greater are
| located to its right. The ordering of the elements in the two partitions
| on the either side of the k-th element in the output array is undefined.
|
| .. versionadded:: 1.8.0
|
| Parameters
| ----------
| kth : int or sequence of ints
| Element index to partition by. The kth element value 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 kth it will partition all elements
| indexed by kth of them into their sorted position at once.
|
| .. deprecated:: 1.22.0
| Passing booleans as index is deprecated.
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'introselect'}, optional
| Selection algorithm. Default is 'introselect'.
| order : str 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, and not all fields need to be specified,
| but unspecified fields will still be used, in the order in which
| they come up in the dtype, to break ties.
|
| See Also
| --------
| numpy.partition : Return a partitioned copy of an array.
| argpartition : Indirect partition.
| sort : Full sort.
|
| Notes
| -----
| See ``np.partition`` for notes on the different algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([3, 4, 2, 1])
| >>> a.partition(3)
| >>> a
| array([2, 1, 3, 4]) # may vary
|
| >>> a.partition((1, 3))
| >>> a
| array([1, 2, 3, 4])
|
| prod(...)
| a.prod(axis=None, dtype=None, out=None, keepdims=False,
| initial=1, where=True)
|
| Return the product of the array elements over the given axis
|
| Refer to `numpy.prod` for full documentation.
|
| See Also
| --------
| numpy.prod : equivalent function
|
| put(...)
| a.put(indices, values, mode='raise')
|
| Set ``a.flat[n] = values[n]`` for all `n` in indices.
|
| Refer to `numpy.put` for full documentation.
|
| See Also
| --------
| numpy.put : equivalent function
|
| ravel(...)
| a.ravel([order])
|
| Return a flattened array.
|
| Refer to `numpy.ravel` for full documentation.
|
| See Also
| --------
| numpy.ravel : equivalent function
|
| ndarray.flat : a flat iterator on the array.
|
| repeat(...)
| a.repeat(repeats, axis=None)
|
| Repeat elements of an array.
|
| Refer to `numpy.repeat` for full documentation.
|
| See Also
| --------
| numpy.repeat : equivalent function
|
| reshape(...)
| a.reshape(shape, /, *, order='C', copy=None)
|
| Returns an array containing the same data with a new shape.
|
| Refer to `numpy.reshape` for full documentation.
|
| See Also
| --------
| numpy.reshape : equivalent function
|
| Notes
| -----
| Unlike the free function `numpy.reshape`, this method on `ndarray` allows
| the elements of the shape parameter to be passed in as separate arguments.
| For example, ``a.reshape(10, 11)`` is equivalent to
| ``a.reshape((10, 11))``.
|
| resize(...)
| a.resize(new_shape, refcheck=True)
|
| Change shape and size of array in-place.
|
| Parameters
| ----------
| new_shape : tuple of ints, or `n` ints
| Shape of resized array.
| refcheck : bool, optional
| If False, reference count will not be checked. Default is True.
|
| Returns
| -------
| None
|
| Raises
| ------
| ValueError
| If `a` does not own its own data or references or views to it exist,
| and the data memory must be changed.
| PyPy only: will always raise if the data memory must be changed, since
| there is no reliable way to determine if references or views to it
| exist.
|
| SystemError
| If the `order` keyword argument is specified. This behaviour is a
| bug in NumPy.
|
| See Also
| --------
| resize : Return a new array with the specified shape.
|
| Notes
| -----
| This reallocates space for the data area if necessary.
|
| Only contiguous arrays (data elements consecutive in memory) can be
| resized.
|
| The purpose of the reference count check is to make sure you
| do not use this array as a buffer for another Python object and then
| reallocate the memory. However, reference counts can increase in
| other ways so if you are sure that you have not shared the memory
| for this array with another Python object, then you may safely set
| `refcheck` to False.
|
| Examples
| --------
| Shrinking an array: array is flattened (in the order that the data are
| stored in memory), resized, and reshaped:
|
| >>> import numpy as np
|
| >>> a = np.array([[0, 1], [2, 3]], order='C')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [1]])
|
| >>> a = np.array([[0, 1], [2, 3]], order='F')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [2]])
|
| Enlarging an array: as above, but missing entries are filled with zeros:
|
| >>> b = np.array([[0, 1], [2, 3]])
| >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
| >>> b
| array([[0, 1, 2],
| [3, 0, 0]])
|
| Referencing an array prevents resizing...
|
| >>> c = a
| >>> a.resize((1, 1))
| Traceback (most recent call last):
| ...
| ValueError: cannot resize an array that references or is referenced ...
|
| Unless `refcheck` is False:
|
| >>> a.resize((1, 1), refcheck=False)
| >>> a
| array([[0]])
| >>> c
| array([[0]])
|
| round(...)
| a.round(decimals=0, out=None)
|
| Return `a` with each element rounded to the given number of decimals.
|
| Refer to `numpy.around` for full documentation.
|
| See Also
| --------
| numpy.around : equivalent function
|
| searchsorted(...)
| a.searchsorted(v, side='left', sorter=None)
|
| Find indices where elements of v should be inserted in a to maintain order.
|
| For full documentation, see `numpy.searchsorted`
|
| See Also
| --------
| numpy.searchsorted : equivalent function
|
| setfield(...)
| a.setfield(val, dtype, offset=0)
|
| Put a value into a specified place in a field defined by a data-type.
|
| Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| bytes into the field.
|
| Parameters
| ----------
| val : object
| Value to be placed in field.
| dtype : dtype object
| Data-type of the field in which to place `val`.
| offset : int, optional
| The number of bytes into the field at which to place `val`.
|
| Returns
| -------
| None
|
| See Also
| --------
| getfield
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.eye(3)
| >>> x.getfield(np.float64)
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
| >>> x.setfield(3, np.int32)
| >>> x.getfield(np.int32)
| array([[3, 3, 3],
| [3, 3, 3],
| [3, 3, 3]], dtype=int32)
| >>> x
| array([[1.0e+000, 1.5e-323, 1.5e-323],
| [1.5e-323, 1.0e+000, 1.5e-323],
| [1.5e-323, 1.5e-323, 1.0e+000]])
| >>> x.setfield(np.eye(3), np.int32)
| >>> x
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
|
| setflags(...)
| a.setflags(write=None, align=None, uic=None)
|
| Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| respectively.
|
| These Boolean-valued flags affect how numpy interprets the memory
| area used by `a` (see Notes below). The ALIGNED flag can only
| be set to True if the data is actually aligned according to the type.
| The WRITEBACKIFCOPY flag can never be set
| to True. The flag WRITEABLE can only be set to True if the array owns its
| own memory, or the ultimate owner of the memory exposes a writeable buffer
| interface, or is a string. (The exception for string is made so that
| unpickling can be done without copying memory.)
|
| Parameters
| ----------
| write : bool, optional
| Describes whether or not `a` can be written to.
| align : bool, optional
| Describes whether or not `a` is aligned properly for its type.
| uic : bool, optional
| Describes whether or not `a` is a copy of another "base" array.
|
| Notes
| -----
| Array flags provide information about how the memory area used
| for the array is to be interpreted. There are 7 Boolean flags
| in use, only three of which can be changed by the user:
| WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
|
| WRITEABLE (W) the data area can be written to;
|
| ALIGNED (A) the data and strides are aligned appropriately for the hardware
| (as determined by the compiler);
|
| WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| called, the base array will be updated with the contents of this array.
|
| All flags can be accessed using the single (upper case) letter as well
| as the full name.
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.array([[3, 1, 7],
| ... [2, 0, 0],
| ... [8, 5, 9]])
| >>> y
| array([[3, 1, 7],
| [2, 0, 0],
| [8, 5, 9]])
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
| >>> y.setflags(write=0, align=0)
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : False
| ALIGNED : False
| WRITEBACKIFCOPY : False
| >>> y.setflags(uic=1)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: cannot set WRITEBACKIFCOPY flag to True
|
| sort(...)
| a.sort(axis=-1, kind=None, order=None)
|
| Sort an array in-place. Refer to `numpy.sort` for full documentation.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
| and 'mergesort' use timsort under the covers and, in general, the
| actual implementation will vary with datatype. The 'mergesort' option
| is retained for backwards compatibility.
|
| .. versionchanged:: 1.15.0
| The 'stable' option was added.
|
| order : str 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, and 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.
|
| See Also
| --------
| numpy.sort : Return a sorted copy of an array.
| numpy.argsort : Indirect sort.
| numpy.lexsort : Indirect stable sort on multiple keys.
| numpy.searchsorted : Find elements in sorted array.
| numpy.partition: Partial sort.
|
| Notes
| -----
| See `numpy.sort` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,4], [3,1]])
| >>> a.sort(axis=1)
| >>> a
| array([[1, 4],
| [1, 3]])
| >>> a.sort(axis=0)
| >>> a
| array([[1, 3],
| [1, 4]])
|
| Use the `order` keyword to specify a field to use when sorting a
| structured array:
|
| >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
| >>> a.sort(order='y')
| >>> a
| array([(b'c', 1), (b'a', 2)],
| dtype=[('x', 'S1'), ('y', '<i8')])
|
| squeeze(...)
| a.squeeze(axis=None)
|
| Remove axes of length one from `a`.
|
| Refer to `numpy.squeeze` for full documentation.
|
| See Also
| --------
| numpy.squeeze : equivalent function
|
| std(...)
| a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the standard deviation of the array elements along given axis.
|
| Refer to `numpy.std` for full documentation.
|
| See Also
| --------
| numpy.std : equivalent function
|
| sum(...)
| a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
|
| Return the sum of the array elements over the given axis.
|
| Refer to `numpy.sum` for full documentation.
|
| See Also
| --------
| numpy.sum : equivalent function
|
| swapaxes(...)
| a.swapaxes(axis1, axis2)
|
| Return a view of the array with `axis1` and `axis2` interchanged.
|
| Refer to `numpy.swapaxes` for full documentation.
|
| See Also
| --------
| numpy.swapaxes : equivalent function
|
| take(...)
| a.take(indices, axis=None, out=None, mode='raise')
|
| Return an array formed from the elements of `a` at the given indices.
|
| Refer to `numpy.take` for full documentation.
|
| See Also
| --------
| numpy.take : equivalent function
|
| to_device(...)
|
| tobytes(...)
| a.tobytes(order='C')
|
| Construct Python bytes containing the raw data bytes in the array.
|
| Constructs Python bytes showing a copy of the raw contents of
| data memory. The bytes object is produced in C-order by default.
| This behavior is controlled by the ``order`` parameter.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| order : {'C', 'F', 'A'}, optional
| Controls the memory layout of the bytes object. 'C' means C-order,
| 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
| Fortran contiguous, 'C' otherwise. Default is 'C'.
|
| Returns
| -------
| s : bytes
| Python bytes exhibiting a copy of `a`'s raw data.
|
| See also
| --------
| frombuffer
| Inverse of this operation, construct a 1-dimensional array from Python
| bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
| >>> x.tobytes()
| b'\x00\x00\x01\x00\x02\x00\x03\x00'
| >>> x.tobytes('C') == x.tobytes()
| True
| >>> x.tobytes('F')
| b'\x00\x00\x02\x00\x01\x00\x03\x00'
|
| tofile(...)
| a.tofile(fid, sep="", format="%s")
|
| Write array to a file as text or binary (default).
|
| Data is always written in 'C' order, independent of the order of `a`.
| The data produced by this method can be recovered using the function
| fromfile().
|
| Parameters
| ----------
| fid : file or str or Path
| An open file object, or a string containing a filename.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| sep : str
| Separator between array items for text output.
| If "" (empty), a binary file is written, equivalent to
| ``file.write(a.tobytes())``.
| format : str
| Format string for text file output.
| Each entry in the array is formatted to text by first converting
| it to the closest Python type, and then using "format" % item.
|
| Notes
| -----
| This is a convenience function for quick storage of array data.
| Information on endianness and precision is lost, so this method is not a
| good choice for files intended to archive data or transport data between
| machines with different endianness. Some of these problems can be overcome
| by outputting the data as text files, at the expense of speed and file
| size.
|
| When fid is a file object, array contents are directly written to the
| file, bypassing the file object's ``write`` method. As a result, tofile
| cannot be used with files objects supporting compression (e.g., GzipFile)
| or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
|
| tolist(...)
| a.tolist()
|
| Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
|
| Return a copy of the array data as a (nested) Python list.
| Data items are converted to the nearest compatible builtin Python type, via
| the `~numpy.ndarray.item` function.
|
| If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
| not be a list at all, but a simple Python scalar.
|
| Parameters
| ----------
| none
|
| Returns
| -------
| y : object, or list of object, or list of list of object, or ...
| The possibly nested list of array elements.
|
| Notes
| -----
| The array may be recreated via ``a = np.array(a.tolist())``, although this
| may sometimes lose precision.
|
| Examples
| --------
| For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
| except that ``tolist`` changes numpy scalars to Python scalars:
|
| >>> import numpy as np
| >>> a = np.uint32([1, 2])
| >>> a_list = list(a)
| >>> a_list
| [1, 2]
| >>> type(a_list[0])
| <class 'numpy.uint32'>
| >>> a_tolist = a.tolist()
| >>> a_tolist
| [1, 2]
| >>> type(a_tolist[0])
| <class 'int'>
|
| Additionally, for a 2D array, ``tolist`` applies recursively:
|
| >>> a = np.array([[1, 2], [3, 4]])
| >>> list(a)
| [array([1, 2]), array([3, 4])]
| >>> a.tolist()
| [[1, 2], [3, 4]]
|
| The base case for this recursion is a 0D array:
|
| >>> a = np.array(1)
| >>> list(a)
| Traceback (most recent call last):
| ...
| TypeError: iteration over a 0-d array
| >>> a.tolist()
| 1
|
| tostring(...)
| a.tostring(order='C')
|
| A compatibility alias for `~ndarray.tobytes`, with exactly the same
| behavior.
|
| Despite its name, it returns :class:`bytes` not :class:`str`\ s.
|
| .. deprecated:: 1.19.0
|
| trace(...)
| a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
|
| Return the sum along diagonals of the array.
|
| Refer to `numpy.trace` for full documentation.
|
| See Also
| --------
| numpy.trace : equivalent function
|
| transpose(...)
| a.transpose(*axes)
|
| Returns a view of the array with axes transposed.
|
| Refer to `numpy.transpose` for full documentation.
|
| Parameters
| ----------
| axes : None, tuple of ints, or `n` ints
|
| * None or no argument: reverses the order of the axes.
|
| * tuple of ints: `i` in the `j`-th place in the tuple means that the
| array's `i`-th axis becomes the transposed array's `j`-th axis.
|
| * `n` ints: same as an n-tuple of the same ints (this form is
| intended simply as a "convenience" alternative to the tuple form).
|
| Returns
| -------
| p : ndarray
| View of the array with its axes suitably permuted.
|
| See Also
| --------
| transpose : Equivalent function.
| ndarray.T : Array property returning the array transposed.
| ndarray.reshape : Give a new shape to an array without changing its data.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.transpose()
| array([[1, 3],
| [2, 4]])
| >>> a.transpose((1, 0))
| array([[1, 3],
| [2, 4]])
| >>> a.transpose(1, 0)
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.transpose()
| array([1, 2, 3, 4])
|
| var(...)
| a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the variance of the array elements, along given axis.
|
| Refer to `numpy.var` for full documentation.
|
| See Also
| --------
| numpy.var : equivalent function
|
| view(...)
| a.view([dtype][, type])
|
| New view of array with the same data.
|
| .. note::
| Passing None for ``dtype`` is different from omitting the parameter,
| since the former invokes ``dtype(None)`` which is an alias for
| ``dtype('float64')``.
|
| Parameters
| ----------
| dtype : data-type or ndarray sub-class, optional
| Data-type descriptor of the returned view, e.g., float32 or int16.
| Omitting it results in the view having the same data-type as `a`.
| This argument can also be specified as an ndarray sub-class, which
| then specifies the type of the returned object (this is equivalent to
| setting the ``type`` parameter).
| type : Python type, optional
| Type of the returned view, e.g., ndarray or matrix. Again, omission
| of the parameter results in type preservation.
|
| Notes
| -----
| ``a.view()`` is used two different ways:
|
| ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| of the array's memory with a different data-type. This can cause a
| reinterpretation of the bytes of memory.
|
| ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| returns an instance of `ndarray_subclass` that looks at the same array
| (same shape, dtype, etc.) This does not cause a reinterpretation of the
| memory.
|
| For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| bytes per entry than the previous dtype (for example, converting a regular
| array to a structured array), then the last axis of ``a`` must be
| contiguous. This axis will be resized in the result.
|
| .. versionchanged:: 1.23.0
| Only the last axis needs to be contiguous. Previously, the entire array
| had to be C-contiguous.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
|
| Viewing array data using a different type and dtype:
|
| >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
| >>> y = x.view(dtype=nonneg, type=np.recarray)
| >>> x["a"]
| array([-1], dtype=int8)
| >>> y.a
| array([255], dtype=uint8)
|
| Creating a view on a structured array so it can be used in calculations
|
| >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
| >>> xv = x.view(dtype=np.int8).reshape(-1,2)
| >>> xv
| array([[1, 2],
| [3, 4]], dtype=int8)
| >>> xv.mean(0)
| array([2., 3.])
|
| Making changes to the view changes the underlying array
|
| >>> xv[0,1] = 20
| >>> x
| array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
|
| Using a view to convert an array to a recarray:
|
| >>> z = x.view(np.recarray)
| >>> z.a
| array([1, 3], dtype=int8)
|
| Views share data:
|
| >>> x[0] = (9, 10)
| >>> z[0]
| np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
|
| Views that change the dtype size (bytes per entry) should normally be
| avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
|
| >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
| >>> y = x[:, ::2]
| >>> y
| array([[1, 3],
| [4, 6]], dtype=int16)
| >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
| Traceback (most recent call last):
| ...
| ValueError: To change to a dtype of a different size, the last axis must be contiguous
| >>> z = y.copy()
| >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
| array([[(1, 3)],
| [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
|
| However, views that change dtype are totally fine for arrays with a
| contiguous last axis, even if the rest of the axes are not C-contiguous:
|
| >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
| >>> x.transpose(1, 0, 2).view(np.int16)
| array([[[ 256, 770],
| [3340, 3854]],
| <BLANKLINE>
| [[1284, 1798],
| [4368, 4882]],
| <BLANKLINE>
| [[2312, 2826],
| [5396, 5910]]], dtype=int16)
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.ndarray:
|
| __class_getitem__(...)
| a.__class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.ndarray` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.ndarray` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.ndarray[Any, np.dtype[Any]]
| numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
| numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.ndarray:
|
| T
| View of the transposed array.
|
| Same as ``self.transpose()``.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.T
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.T
| array([1, 2, 3, 4])
|
| See Also
| --------
| transpose
|
| __array_interface__
| Array protocol: Python side.
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: C-struct side.
|
| base
| Base object if memory is from some other object.
|
| Examples
| --------
| The base of an array that owns its memory is None:
|
| >>> import numpy as np
| >>> x = np.array([1,2,3,4])
| >>> x.base is None
| True
|
| Slicing creates a view, whose memory is shared with x:
|
| >>> y = x[2:]
| >>> y.base is x
| True
|
| ctypes
| An object to simplify the interaction of the array with the ctypes
| module.
|
| This attribute creates an object that makes it easier to use arrays
| when calling shared libraries with the ctypes module. The returned
| object has, among others, data, shape, and strides attributes (see
| Notes below) which themselves return ctypes objects that can be used
| as arguments to a shared library.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| c : Python object
| Possessing attributes data, shape, strides, etc.
|
| See Also
| --------
| numpy.ctypeslib
|
| Notes
| -----
| Below are the public attributes of this object which were documented
| in "Guide to NumPy" (we have omitted undocumented public attributes,
| as well as documented private attributes):
|
| .. autoattribute:: numpy._core._internal._ctypes.data
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.shape
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.strides
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.data_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.shape_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.strides_as
| :noindex:
|
| If the ctypes module is not available, then the ctypes attribute
| of array objects still returns something useful, but ctypes objects
| are not returned and errors may be raised instead. In particular,
| the object will still have the ``as_parameter`` attribute which will
| return an integer equal to the data attribute.
|
| Examples
| --------
| >>> import numpy as np
| >>> import ctypes
| >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| >>> x
| array([[0, 1],
| [2, 3]], dtype=int32)
| >>> x.ctypes.data
| 31962608 # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| c_uint(0)
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| c_ulong(4294967296)
| >>> x.ctypes.shape
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| >>> x.ctypes.strides
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
|
| data
| Python buffer object pointing to the start of the array's data.
|
| device
|
| dtype
| Data-type of the array's elements.
|
| .. warning::
|
| Setting ``arr.dtype`` is discouraged and may be deprecated in the
| future. Setting will replace the ``dtype`` without modifying the
| memory (see also `ndarray.view` and `ndarray.astype`).
|
| Parameters
| ----------
| None
|
| Returns
| -------
| d : numpy dtype object
|
| See Also
| --------
| ndarray.astype : Cast the values contained in the array to a new data-type.
| ndarray.view : Create a view of the same data but a different data-type.
| numpy.dtype
|
| Examples
| --------
| >>> x
| array([[0, 1],
| [2, 3]])
| >>> x.dtype
| dtype('int32')
| >>> type(x.dtype)
| <type 'numpy.dtype'>
|
| flags
| Information about the memory layout of the array.
|
| Attributes
| ----------
| C_CONTIGUOUS (C)
| The data is in a single, C-style contiguous segment.
| F_CONTIGUOUS (F)
| The data is in a single, Fortran-style contiguous segment.
| OWNDATA (O)
| The array owns the memory it uses or borrows it from another object.
| WRITEABLE (W)
| The data area can be written to. Setting this to False locks
| the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| from its base array at creation time, but a view of a writeable
| array may be subsequently locked while the base array remains writeable.
| (The opposite is not true, in that a view of a locked array may not
| be made writeable. However, currently, locking a base object does not
| lock any views that already reference it, so under that circumstance it
| is possible to alter the contents of a locked array via a previously
| created writeable view onto it.) Attempting to change a non-writeable
| array raises a RuntimeError exception.
| ALIGNED (A)
| The data and all elements are aligned appropriately for the hardware.
| WRITEBACKIFCOPY (X)
| This array is a copy of some other array. The C-API function
| PyArray_ResolveWritebackIfCopy must be called before deallocating
| to the base array will be updated with the contents of this array.
| FNC
| F_CONTIGUOUS and not C_CONTIGUOUS.
| FORC
| F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| BEHAVED (B)
| ALIGNED and WRITEABLE.
| CARRAY (CA)
| BEHAVED and C_CONTIGUOUS.
| FARRAY (FA)
| BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
|
| Notes
| -----
| The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| names are only supported in dictionary access.
|
| Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| changed by the user, via direct assignment to the attribute or dictionary
| entry, or by calling `ndarray.setflags`.
|
| The array flags cannot be set arbitrarily:
|
| - WRITEBACKIFCOPY can only be set ``False``.
| - ALIGNED can only be set ``True`` if the data is truly aligned.
| - WRITEABLE can only be set ``True`` if the array owns its own memory
| or the ultimate owner of the memory exposes a writeable buffer
| interface or is a string.
|
| Arrays can be both C-style and Fortran-style contiguous simultaneously.
| This is clear for 1-dimensional arrays, but can also be true for higher
| dimensional arrays.
|
| Even for contiguous arrays a stride for a given dimension
| ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| or the array has no elements.
| It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| Fortran-style contiguous arrays is true.
|
| flat
| A 1-D iterator over the array.
|
| This is a `numpy.flatiter` instance, which acts similarly to, but is not
| a subclass of, Python's built-in iterator object.
|
| See Also
| --------
| flatten : Return a copy of the array collapsed into one dimension.
|
| flatiter
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(1, 7).reshape(2, 3)
| >>> x
| array([[1, 2, 3],
| [4, 5, 6]])
| >>> x.flat[3]
| 4
| >>> x.T
| array([[1, 4],
| [2, 5],
| [3, 6]])
| >>> x.T.flat[3]
| 5
| >>> type(x.flat)
| <class 'numpy.flatiter'>
|
| An assignment example:
|
| >>> x.flat = 3; x
| array([[3, 3, 3],
| [3, 3, 3]])
| >>> x.flat[[1,4]] = 1; x
| array([[3, 1, 3],
| [3, 1, 3]])
|
| imag
| The imaginary part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.imag
| array([ 0. , 0.70710678])
| >>> x.imag.dtype
| dtype('float64')
|
| itemset
|
| itemsize
| Length of one array element in bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1,2,3], dtype=np.float64)
| >>> x.itemsize
| 8
| >>> x = np.array([1,2,3], dtype=np.complex128)
| >>> x.itemsize
| 16
|
| mT
| View of the matrix transposed array.
|
| The matrix transpose is the transpose of the last two dimensions, even
| if the array is of higher dimension.
|
| .. versionadded:: 2.0
|
| Raises
| ------
| ValueError
| If the array is of dimension less than 2.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.mT
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.arange(8).reshape((2, 2, 2))
| >>> a
| array([[[0, 1],
| [2, 3]],
| <BLANKLINE>
| [[4, 5],
| [6, 7]]])
| >>> a.mT
| array([[[0, 2],
| [1, 3]],
| <BLANKLINE>
| [[4, 6],
| [5, 7]]])
|
| nbytes
| Total bytes consumed by the elements of the array.
|
| Notes
| -----
| Does not include memory consumed by non-element attributes of the
| array object.
|
| See Also
| --------
| sys.getsizeof
| Memory consumed by the object itself without parents in case view.
| This does include memory consumed by non-element attributes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3,5,2), dtype=np.complex128)
| >>> x.nbytes
| 480
| >>> np.prod(x.shape) * x.itemsize
| 480
|
| ndim
| Number of array dimensions.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3])
| >>> x.ndim
| 1
| >>> y = np.zeros((2, 3, 4))
| >>> y.ndim
| 3
|
| newbyteorder
|
| ptp
|
| real
| The real part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.real
| array([ 1. , 0.70710678])
| >>> x.real.dtype
| dtype('float64')
|
| See Also
| --------
| numpy.real : equivalent function
|
| shape
| Tuple of array dimensions.
|
| The shape property is usually used to get the current shape of an array,
| but may also be used to reshape the array in-place by assigning a tuple of
| array dimensions to it. As with `numpy.reshape`, one of the new shape
| dimensions can be -1, in which case its value is inferred from the size of
| the array and the remaining dimensions. Reshaping an array in-place will
| fail if a copy is required.
|
| .. warning::
|
| Setting ``arr.shape`` is discouraged and may be deprecated in the
| future. Using `ndarray.reshape` is the preferred approach.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3, 4])
| >>> x.shape
| (4,)
| >>> y = np.zeros((2, 3, 4))
| >>> y.shape
| (2, 3, 4)
| >>> y.shape = (3, 8)
| >>> y
| array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| >>> y.shape = (3, 6)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: total size of new array must be unchanged
| >>> np.zeros((4,2))[::2].shape = (-1,)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| AttributeError: Incompatible shape for in-place modification. Use
| `.reshape()` to make a copy with the desired shape.
|
| See Also
| --------
| numpy.shape : Equivalent getter function.
| numpy.reshape : Function similar to setting ``shape``.
| ndarray.reshape : Method similar to setting ``shape``.
|
| size
| Number of elements in the array.
|
| Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| dimensions.
|
| Notes
| -----
| `a.size` returns a standard arbitrary precision Python integer. This
| may not be the case with other methods of obtaining the same value
| (like the suggested ``np.prod(a.shape)``, which returns an instance
| of ``np.int_``), and may be relevant if the value is used further in
| calculations that may overflow a fixed size integer type.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| >>> x.size
| 30
| >>> np.prod(x.shape)
| 30
|
| strides
| Tuple of bytes to step in each dimension when traversing an array.
|
| The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| is::
|
| offset = sum(np.array(i) * a.strides)
|
| A more detailed explanation of strides can be found in
| :ref:`arrays.ndarray`.
|
| .. warning::
|
| Setting ``arr.strides`` is discouraged and may be deprecated in the
| future. `numpy.lib.stride_tricks.as_strided` should be preferred
| to create a new view of the same data in a safer way.
|
| Notes
| -----
| Imagine an array of 32-bit integers (each 4 bytes)::
|
| x = np.array([[0, 1, 2, 3, 4],
| [5, 6, 7, 8, 9]], dtype=np.int32)
|
| This array is stored in memory as 40 bytes, one after the other
| (known as a contiguous block of memory). The strides of an array tell
| us how many bytes we have to skip in memory to move to the next position
| along a certain axis. For example, we have to skip 4 bytes (1 value) to
| move to the next column, but 20 bytes (5 values) to get to the same
| position in the next row. As such, the strides for the array `x` will be
| ``(20, 4)``.
|
| See Also
| --------
| numpy.lib.stride_tricks.as_strided
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| >>> y
| array([[[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]],
| [[12, 13, 14, 15],
| [16, 17, 18, 19],
| [20, 21, 22, 23]]])
| >>> y.strides
| (48, 16, 4)
| >>> y[1,1,1]
| 17
| >>> offset=sum(y.strides * np.array((1,1,1)))
| >>> offset/y.itemsize
| 17
|
| >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| >>> x.strides
| (32, 4, 224, 1344)
| >>> i = np.array([3,5,2,2])
| >>> offset = sum(i * x.strides)
| >>> x[3,5,2,2]
| 813
| >>> offset / x.itemsize
| 813
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.ndarray:
|
| __hash__ = None
class record(void)
| A data-type scalar that allows field access as attribute lookup.
|
| Method resolution order:
| record
| void
| flexible
| generic
| builtins.object
|
| Methods defined here:
|
| __getattribute__(self, attr) from numpy._core.records.record
| Return getattr(self, name).
|
| __getitem__(self, indx) from numpy._core.records.record
| Return self[key].
|
| __repr__(self) from numpy._core.records.record
| Return repr(self).
|
| __setattr__(self, attr, val) from numpy._core.records.record
| Implement setattr(self, name, value).
|
| __str__(self) from numpy._core.records.record
| Return str(self).
|
| pprint(self) from numpy._core.records.record
| Pretty-print all fields.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from void:
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| ----------------------------------------------------------------------
| Static methods inherited from void:
|
| __new__(*args, **kwargs) class method of numpy.void
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from void:
|
| base
| base object
|
| dtype
| dtype object
|
| flags
| integer value of flags
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __bool__(self, /)
| True if self else False
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| NumPy array scalar formatter
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| Helper for pickle.
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setstate__(...)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| data
| Pointer to start of data.
|
| device
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
FUNCTIONS
array(obj, dtype=None, shape=None, offset=0, strides=None, formats=None, names=None, titles=None, aligned=False, byteorder=None, copy=True)
Construct a record array from a wide-variety of objects.
A general-purpose record array constructor that dispatches to the
appropriate `recarray` creation function based on the inputs (see Notes).
Parameters
----------
obj : any
Input object. See Notes for details on how various input types are
treated.
dtype : data-type, optional
Valid dtype for array.
shape : int or tuple of ints, optional
Shape of each array.
offset : int, optional
Position in the file or buffer to start reading from.
strides : tuple of ints, optional
Buffer (`buf`) is interpreted according to these strides (strides
define how many bytes each array element, row, column, etc.
occupy in memory).
formats, names, titles, aligned, byteorder :
If `dtype` is ``None``, these arguments are passed to
`numpy.format_parser` to construct a dtype. See that function for
detailed documentation.
copy : bool, optional
Whether to copy the input object (True), or to use a reference instead.
This option only applies when the input is an ndarray or recarray.
Defaults to True.
Returns
-------
np.recarray
Record array created from the specified object.
Notes
-----
If `obj` is ``None``, then call the `~numpy.recarray` constructor. If
`obj` is a string, then call the `fromstring` constructor. If `obj` is a
list or a tuple, then if the first object is an `~numpy.ndarray`, call
`fromarrays`, otherwise call `fromrecords`. If `obj` is a
`~numpy.recarray`, then make a copy of the data in the recarray
(if ``copy=True``) and use the new formats, names, and titles. If `obj`
is a file, then call `fromfile`. Finally, if obj is an `ndarray`, then
return ``obj.view(recarray)``, making a copy of the data if ``copy=True``.
Examples
--------
>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.rec.array(a)
rec.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
dtype=int64)
>>> b = [(1, 1), (2, 4), (3, 9)]
>>> c = np.rec.array(b, formats = ['i2', 'f2'], names = ('x', 'y'))
>>> c
rec.array([(1, 1.), (2, 4.), (3, 9.)],
dtype=[('x', '<i2'), ('y', '<f2')])
>>> c.x
array([1, 2, 3], dtype=int16)
>>> c.y
array([1., 4., 9.], dtype=float16)
>>> r = np.rec.array(['abc','def'], names=['col1','col2'])
>>> print(r.col1)
abc
>>> r.col1
array('abc', dtype='<U3')
>>> r.col2
array('def', dtype='<U3')
find_duplicate(list)
Find duplication in a list, return a list of duplicated elements
fromarrays(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None)
Create a record array from a (flat) list of arrays
Parameters
----------
arrayList : list or tuple
List of array-like objects (such as lists, tuples,
and ndarrays).
dtype : data-type, optional
valid dtype for all arrays
shape : int or tuple of ints, optional
Shape of the resulting array. If not provided, inferred from
``arrayList[0]``.
formats, names, titles, aligned, byteorder :
If `dtype` is ``None``, these arguments are passed to
`numpy.rec.format_parser` to construct a dtype. See that function for
detailed documentation.
Returns
-------
np.recarray
Record array consisting of given arrayList columns.
Examples
--------
>>> x1=np.array([1,2,3,4])
>>> x2=np.array(['a','dd','xyz','12'])
>>> x3=np.array([1.1,2,3,4])
>>> r = np.rec.fromarrays([x1,x2,x3],names='a,b,c')
>>> print(r[1])
(2, 'dd', 2.0) # may vary
>>> x1[1]=34
>>> r.a
array([1, 2, 3, 4])
>>> x1 = np.array([1, 2, 3, 4])
>>> x2 = np.array(['a', 'dd', 'xyz', '12'])
>>> x3 = np.array([1.1, 2, 3,4])
>>> r = np.rec.fromarrays(
... [x1, x2, x3],
... dtype=np.dtype([('a', np.int32), ('b', 'S3'), ('c', np.float32)]))
>>> r
rec.array([(1, b'a', 1.1), (2, b'dd', 2. ), (3, b'xyz', 3. ),
(4, b'12', 4. )],
dtype=[('a', '<i4'), ('b', 'S3'), ('c', '<f4')])
fromfile(fd, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None)
Create an array from binary file data
Parameters
----------
fd : str or file type
If file is a string or a path-like object then that file is opened,
else it is assumed to be a file object. The file object must
support random access (i.e. it must have tell and seek methods).
dtype : data-type, optional
valid dtype for all arrays
shape : int or tuple of ints, optional
shape of each array.
offset : int, optional
Position in the file to start reading from.
formats, names, titles, aligned, byteorder :
If `dtype` is ``None``, these arguments are passed to
`numpy.format_parser` to construct a dtype. See that function for
detailed documentation
Returns
-------
np.recarray
record array consisting of data enclosed in file.
Examples
--------
>>> from tempfile import TemporaryFile
>>> a = np.empty(10,dtype='f8,i4,a5')
>>> a[5] = (0.5,10,'abcde')
>>>
>>> fd=TemporaryFile()
>>> a = a.view(a.dtype.newbyteorder('<'))
>>> a.tofile(fd)
>>>
>>> _ = fd.seek(0)
>>> r=np.rec.fromfile(fd, formats='f8,i4,a5', shape=10,
... byteorder='<')
>>> print(r[5])
(0.5, 10, b'abcde')
>>> r.shape
(10,)
fromrecords(recList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None)
Create a recarray from a list of records in text form.
Parameters
----------
recList : sequence
data in the same field may be heterogeneous - they will be promoted
to the highest data type.
dtype : data-type, optional
valid dtype for all arrays
shape : int or tuple of ints, optional
shape of each array.
formats, names, titles, aligned, byteorder :
If `dtype` is ``None``, these arguments are passed to
`numpy.format_parser` to construct a dtype. See that function for
detailed documentation.
If both `formats` and `dtype` are None, then this will auto-detect
formats. Use list of tuples rather than list of lists for faster
processing.
Returns
-------
np.recarray
record array consisting of given recList rows.
Examples
--------
>>> r=np.rec.fromrecords([(456,'dbe',1.2),(2,'de',1.3)],
... names='col1,col2,col3')
>>> print(r[0])
(456, 'dbe', 1.2)
>>> r.col1
array([456, 2])
>>> r.col2
array(['dbe', 'de'], dtype='<U3')
>>> import pickle
>>> pickle.loads(pickle.dumps(r))
rec.array([(456, 'dbe', 1.2), ( 2, 'de', 1.3)],
dtype=[('col1', '<i8'), ('col2', '<U3'), ('col3', '<f8')])
fromstring(datastring, dtype=None, shape=None, offset=0, formats=None, names=None, titles=None, aligned=False, byteorder=None)
Create a record array from binary data
Note that despite the name of this function it does not accept `str`
instances.
Parameters
----------
datastring : bytes-like
Buffer of binary data
dtype : data-type, optional
Valid dtype for all arrays
shape : int or tuple of ints, optional
Shape of each array.
offset : int, optional
Position in the buffer to start reading from.
formats, names, titles, aligned, byteorder :
If `dtype` is ``None``, these arguments are passed to
`numpy.format_parser` to construct a dtype. See that function for
detailed documentation.
Returns
-------
np.recarray
Record array view into the data in datastring. This will be readonly
if `datastring` is readonly.
See Also
--------
numpy.frombuffer
Examples
--------
>>> a = b'\x01\x02\x03abc'
>>> np.rec.fromstring(a, dtype='u1,u1,u1,S3')
rec.array([(1, 2, 3, b'abc')],
dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1'), ('f3', 'S3')])
>>> grades_dtype = [('Name', (np.str_, 10)), ('Marks', np.float64),
... ('GradeLevel', np.int32)]
>>> grades_array = np.array([('Sam', 33.3, 3), ('Mike', 44.4, 5),
... ('Aadi', 66.6, 6)], dtype=grades_dtype)
>>> np.rec.fromstring(grades_array.tobytes(), dtype=grades_dtype)
rec.array([('Sam', 33.3, 3), ('Mike', 44.4, 5), ('Aadi', 66.6, 6)],
dtype=[('Name', '<U10'), ('Marks', '<f8'), ('GradeLevel', '<i4')])
>>> s = '\x01\x02\x03abc'
>>> np.rec.fromstring(s, dtype='u1,u1,u1,S3')
Traceback (most recent call last):
...
TypeError: a bytes-like object is required, not 'str'
DATA
__all__ = ['record', 'recarray', 'format_parser', 'fromarrays', 'fromr...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\rec\__init__.py
numpy.recarray
Python Library Documentation: class recarray in module numpy.rec
class recarray(numpy.ndarray)
| recarray(shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, order='C')
|
| Construct an ndarray that allows field access using attributes.
|
| Arrays may have a data-types containing fields, analogous
| to columns in a spread sheet. An example is ``[(x, int), (y, float)]``,
| where each entry in the array is a pair of ``(int, float)``. Normally,
| these attributes are accessed using dictionary lookups such as ``arr['x']``
| and ``arr['y']``. Record arrays allow the fields to be accessed as members
| of the array, using ``arr.x`` and ``arr.y``.
|
| Parameters
| ----------
| shape : tuple
| Shape of output array.
| dtype : data-type, optional
| The desired data-type. By default, the data-type is determined
| from `formats`, `names`, `titles`, `aligned` and `byteorder`.
| formats : list of data-types, optional
| A list containing the data-types for the different columns, e.g.
| ``['i4', 'f8', 'i4']``. `formats` does *not* support the new
| convention of using types directly, i.e. ``(int, float, int)``.
| Note that `formats` must be a list, not a tuple.
| Given that `formats` is somewhat limited, we recommend specifying
| `dtype` instead.
| names : tuple of str, optional
| The name of each column, e.g. ``('x', 'y', 'z')``.
| buf : buffer, optional
| By default, a new array is created of the given shape and data-type.
| If `buf` is specified and is an object exposing the buffer interface,
| the array will use the memory from the existing buffer. In this case,
| the `offset` and `strides` keywords are available.
|
| Other Parameters
| ----------------
| titles : tuple of str, optional
| Aliases for column names. For example, if `names` were
| ``('x', 'y', 'z')`` and `titles` is
| ``('x_coordinate', 'y_coordinate', 'z_coordinate')``, then
| ``arr['x']`` is equivalent to both ``arr.x`` and ``arr.x_coordinate``.
| byteorder : {'<', '>', '='}, optional
| Byte-order for all fields.
| aligned : bool, optional
| Align the fields in memory as the C-compiler would.
| strides : tuple of ints, optional
| Buffer (`buf`) is interpreted according to these strides (strides
| define how many bytes each array element, row, column, etc.
| occupy in memory).
| offset : int, optional
| Start reading buffer (`buf`) from this offset onwards.
| order : {'C', 'F'}, optional
| Row-major (C-style) or column-major (Fortran-style) order.
|
| Returns
| -------
| rec : recarray
| Empty array of the given shape and type.
|
| See Also
| --------
| numpy.rec.fromrecords : Construct a record array from data.
| numpy.record : fundamental data-type for `recarray`.
| numpy.rec.format_parser : determine data-type from formats, names, titles.
|
| Notes
| -----
| This constructor can be compared to ``empty``: it creates a new record
| array but does not fill it with data. To create a record array from data,
| use one of the following methods:
|
| 1. Create a standard ndarray and convert it to a record array,
| using ``arr.view(np.recarray)``
| 2. Use the `buf` keyword.
| 3. Use `np.rec.fromrecords`.
|
| Examples
| --------
| Create an array with two fields, ``x`` and ``y``:
|
| >>> import numpy as np
| >>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', '<f8'), ('y', '<i8')])
| >>> x
| array([(1., 2), (3., 4)], dtype=[('x', '<f8'), ('y', '<i8')])
|
| >>> x['x']
| array([1., 3.])
|
| View the array as a record array:
|
| >>> x = x.view(np.recarray)
|
| >>> x.x
| array([1., 3.])
|
| >>> x.y
| array([2, 4])
|
| Create a new, empty record array:
|
| >>> np.recarray((2,),
| ... dtype=[('x', int), ('y', float), ('z', int)]) #doctest: +SKIP
| rec.array([(-1073741821, 1.2249118382103472e-301, 24547520),
| (3471280, 1.2134086255804012e-316, 0)],
| dtype=[('x', '<i4'), ('y', '<f8'), ('z', '<i4')])
|
| Method resolution order:
| recarray
| numpy.ndarray
| builtins.object
|
| Methods defined here:
|
| __array_finalize__(self, obj) from numpy._core.records.recarray
| a.__array_finalize__(obj, /)
|
| Present so subclasses can call super. Does nothing.
|
| __getattribute__(self, attr) from numpy._core.records.recarray
| Return getattr(self, name).
|
| __getitem__(self, indx) from numpy._core.records.recarray
| Return self[key].
|
| __repr__(self) from numpy._core.records.recarray
| Return repr(self).
|
| __setattr__(self, attr, val) from numpy._core.records.recarray
| Implement setattr(self, name, value).
|
| field(self, attr, val=None) from numpy._core.records.recarray
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(subtype, shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, order='C') from numpy._core.records.recarray
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| ----------------------------------------------------------------------
| Methods inherited from numpy.ndarray:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| a.__array__([dtype], *, copy=None)
|
| For ``dtype`` parameter it returns a new reference to self if
| ``dtype`` is not given or it matches array's data type.
| A new array of provided data type is returned if ``dtype``
| is different from the current data type of the array.
| For ``copy`` parameter it returns a new reference to self if
| ``copy=False`` or ``copy=None`` and copying isn't enforced by ``dtype``
| parameter. The method returns a new array for ``copy=True``, regardless of
| ``dtype`` parameter.
|
| A more detailed explanation of the ``__array__`` interface
| can be found in :ref:`dunder_array.interface`.
|
| __array_function__(...)
|
| __array_namespace__(...)
|
| __array_ufunc__(...)
|
| __array_wrap__(...)
| a.__array_wrap__(array[, context], /)
|
| Returns a view of `array` with the same type as self.
|
| __bool__(self, /)
| True if self else False
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __complex__(...)
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __copy__(...)
| a.__copy__()
|
| Used if :func:`copy.copy` is called on an array. Returns a copy of the array.
|
| Equivalent to ``a.copy(order='K')``.
|
| __deepcopy__(...)
| a.__deepcopy__(memo, /)
|
| Used if :func:`copy.deepcopy` is called on an array.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __dlpack__(...)
| a.__dlpack__(*, stream=None, max_version=None, dl_device=None, copy=None)
|
| DLPack Protocol: Part of the Array API.
|
| __dlpack_device__(...)
| a.__dlpack_device__()
|
| DLPack Protocol: Part of the Array API.
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| Default object formatter.
|
| Return str(self) if format_spec is empty. Raise TypeError otherwise.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Return self+=value.
|
| __iand__(self, value, /)
| Return self&=value.
|
| __ifloordiv__(self, value, /)
| Return self//=value.
|
| __ilshift__(self, value, /)
| Return self<<=value.
|
| __imatmul__(self, value, /)
| Return self@=value.
|
| __imod__(self, value, /)
| Return self%=value.
|
| __imul__(self, value, /)
| Return self*=value.
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __ior__(self, value, /)
| Return self|=value.
|
| __ipow__(self, value, /)
| Return self**=value.
|
| __irshift__(self, value, /)
| Return self>>=value.
|
| __isub__(self, value, /)
| Return self-=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __itruediv__(self, value, /)
| Return self/=value.
|
| __ixor__(self, value, /)
| Return self^=value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __matmul__(self, value, /)
| Return self@value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| a.__reduce__()
|
| For pickling.
|
| __reduce_ex__(...)
| Helper for pickle.
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmatmul__(self, value, /)
| Return value@self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __setstate__(...)
| a.__setstate__(state, /)
|
| For unpickling.
|
| The `state` argument must be a sequence that contains the following
| elements:
|
| Parameters
| ----------
| version : int
| optional pickle version. If omitted defaults to 0.
| shape : tuple
| dtype : data-type
| isFortran : bool
| rawdata : string or list
| a binary string with the data (or a list if 'a' is an object array)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| a.all(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if all elements evaluate to True.
|
| Refer to `numpy.all` for full documentation.
|
| See Also
| --------
| numpy.all : equivalent function
|
| any(...)
| a.any(axis=None, out=None, keepdims=False, *, where=True)
|
| Returns True if any of the elements of `a` evaluate to True.
|
| Refer to `numpy.any` for full documentation.
|
| See Also
| --------
| numpy.any : equivalent function
|
| argmax(...)
| a.argmax(axis=None, out=None, *, keepdims=False)
|
| Return indices of the maximum values along the given axis.
|
| Refer to `numpy.argmax` for full documentation.
|
| See Also
| --------
| numpy.argmax : equivalent function
|
| argmin(...)
| a.argmin(axis=None, out=None, *, keepdims=False)
|
| Return indices of the minimum values along the given axis.
|
| Refer to `numpy.argmin` for detailed documentation.
|
| See Also
| --------
| numpy.argmin : equivalent function
|
| argpartition(...)
| a.argpartition(kth, axis=-1, kind='introselect', order=None)
|
| Returns the indices that would partition this array.
|
| Refer to `numpy.argpartition` for full documentation.
|
| .. versionadded:: 1.8.0
|
| See Also
| --------
| numpy.argpartition : equivalent function
|
| argsort(...)
| a.argsort(axis=-1, kind=None, order=None)
|
| Returns the indices that would sort this array.
|
| Refer to `numpy.argsort` for full documentation.
|
| See Also
| --------
| numpy.argsort : equivalent function
|
| astype(...)
| a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)
|
| Copy of the array, cast to a specified type.
|
| Parameters
| ----------
| dtype : str or dtype
| Typecode or data-type to which the array is cast.
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout order of the result.
| '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.
| Default is 'K'.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| Controls what kind of data casting may occur. Defaults to 'unsafe'
| for backwards compatibility.
|
| * '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.
| subok : bool, optional
| If True, then sub-classes will be passed-through (default), otherwise
| the returned array will be forced to be a base-class array.
| copy : bool, optional
| By default, astype always returns a newly allocated array. If this
| is set to false, and the `dtype`, `order`, and `subok`
| requirements are satisfied, the input array is returned instead
| of a copy.
|
| Returns
| -------
| arr_t : ndarray
| Unless `copy` is False and the other conditions for returning the input
| array are satisfied (see description for `copy` input parameter), `arr_t`
| is a new array of the same shape as the input array, with dtype, order
| given by `dtype`, `order`.
|
| Notes
| -----
| .. versionchanged:: 1.17.0
| Casting between a simple data type and a structured one is possible only
| for "unsafe" casting. Casting to multiple fields is allowed, but
| casting from multiple fields is not.
|
| .. versionchanged:: 1.9.0
| Casting from numeric to string types in 'safe' casting mode requires
| that the string dtype length is long enough to store the max
| integer/float value converted.
|
| Raises
| ------
| ComplexWarning
| When casting from complex to float or int. To avoid this,
| one should use ``a.real.astype(t)``.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 2.5])
| >>> x
| array([1. , 2. , 2.5])
|
| >>> x.astype(int)
| array([1, 2, 2])
|
| byteswap(...)
| a.byteswap(inplace=False)
|
| Swap the bytes of the array elements
|
| Toggle between low-endian and big-endian data representation by
| returning a byteswapped array, optionally swapped in-place.
| Arrays of byte-strings are not swapped. The real and imaginary
| parts of a complex number are swapped individually.
|
| Parameters
| ----------
| inplace : bool, optional
| If ``True``, swap bytes in-place, default is ``False``.
|
| Returns
| -------
| out : ndarray
| The byteswapped array. If `inplace` is ``True``, this is
| a view to self.
|
| Examples
| --------
| >>> import numpy as np
| >>> A = np.array([1, 256, 8755], dtype=np.int16)
| >>> list(map(hex, A))
| ['0x1', '0x100', '0x2233']
| >>> A.byteswap(inplace=True)
| array([ 256, 1, 13090], dtype=int16)
| >>> list(map(hex, A))
| ['0x100', '0x1', '0x3322']
|
| Arrays of byte-strings are not swapped
|
| >>> A = np.array([b'ceg', b'fac'])
| >>> A.byteswap()
| array([b'ceg', b'fac'], dtype='|S3')
|
| ``A.view(A.dtype.newbyteorder()).byteswap()`` produces an array with
| the same values but different representation in memory
|
| >>> A = np.array([1, 2, 3])
| >>> A.view(np.uint8)
| array([1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
| 0, 0], dtype=uint8)
| >>> A.view(A.dtype.newbyteorder()).byteswap(inplace=True)
| array([1, 2, 3])
| >>> A.view(np.uint8)
| array([0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
| 0, 3], dtype=uint8)
|
| choose(...)
| a.choose(choices, out=None, mode='raise')
|
| Use an index array to construct a new array from a set of choices.
|
| Refer to `numpy.choose` for full documentation.
|
| See Also
| --------
| numpy.choose : equivalent function
|
| clip(...)
| a.clip(min=None, max=None, out=None, **kwargs)
|
| Return an array whose values are limited to ``[min, max]``.
| One of max or min must be given.
|
| Refer to `numpy.clip` for full documentation.
|
| See Also
| --------
| numpy.clip : equivalent function
|
| compress(...)
| a.compress(condition, axis=None, out=None)
|
| Return selected slices of this array along given axis.
|
| Refer to `numpy.compress` for full documentation.
|
| See Also
| --------
| numpy.compress : equivalent function
|
| conj(...)
| a.conj()
|
| Complex-conjugate all elements.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| conjugate(...)
| a.conjugate()
|
| Return the complex conjugate, element-wise.
|
| Refer to `numpy.conjugate` for full documentation.
|
| See Also
| --------
| numpy.conjugate : equivalent function
|
| copy(...)
| a.copy(order='C')
|
| Return a copy of the array.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| Controls the memory layout of the copy. 'C' means C-order,
| 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
| 'C' otherwise. 'K' means match the layout of `a` as closely
| as possible. (Note that this function and :func:`numpy.copy` are very
| similar but have different default values for their order=
| arguments, and this function always passes sub-classes through.)
|
| See also
| --------
| numpy.copy : Similar function with different default behavior
| numpy.copyto
|
| Notes
| -----
| This function is the preferred method for creating an array copy. The
| function :func:`numpy.copy` is similar, but it defaults to using order 'K',
| and will not pass sub-classes through by default.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[1,2,3],[4,5,6]], order='F')
|
| >>> y = x.copy()
|
| >>> x.fill(0)
|
| >>> x
| array([[0, 0, 0],
| [0, 0, 0]])
|
| >>> y
| array([[1, 2, 3],
| [4, 5, 6]])
|
| >>> y.flags['C_CONTIGUOUS']
| True
|
| For arrays containing Python objects (e.g. dtype=object),
| the copy is a shallow one. The new array will contain the
| same object which may lead to surprises if that object can
| be modified (is mutable):
|
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> b = a.copy()
| >>> b[2][0] = 10
| >>> a
| array([1, 'm', list([10, 3, 4])], dtype=object)
|
| To ensure all elements within an ``object`` array are copied,
| use `copy.deepcopy`:
|
| >>> import copy
| >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
| >>> c = copy.deepcopy(a)
| >>> c[2][0] = 10
| >>> c
| array([1, 'm', list([10, 3, 4])], dtype=object)
| >>> a
| array([1, 'm', list([2, 3, 4])], dtype=object)
|
| cumprod(...)
| a.cumprod(axis=None, dtype=None, out=None)
|
| Return the cumulative product of the elements along the given axis.
|
| Refer to `numpy.cumprod` for full documentation.
|
| See Also
| --------
| numpy.cumprod : equivalent function
|
| cumsum(...)
| a.cumsum(axis=None, dtype=None, out=None)
|
| Return the cumulative sum of the elements along the given axis.
|
| Refer to `numpy.cumsum` for full documentation.
|
| See Also
| --------
| numpy.cumsum : equivalent function
|
| diagonal(...)
| a.diagonal(offset=0, axis1=0, axis2=1)
|
| Return specified diagonals. In NumPy 1.9 the returned array is a
| read-only view instead of a copy as in previous NumPy versions. In
| a future version the read-only restriction will be removed.
|
| Refer to :func:`numpy.diagonal` for full documentation.
|
| See Also
| --------
| numpy.diagonal : equivalent function
|
| dot(...)
|
| dump(...)
| a.dump(file)
|
| Dump a pickle of the array to the specified file.
| The array can be read back with pickle.load or numpy.load.
|
| Parameters
| ----------
| file : str or Path
| A string naming the dump file.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| dumps(...)
| a.dumps()
|
| Returns the pickle of the array as a string.
| pickle.loads will convert the string back to an array.
|
| Parameters
| ----------
| None
|
| fill(...)
| a.fill(value)
|
| Fill the array with a scalar value.
|
| Parameters
| ----------
| value : scalar
| All elements of `a` will be assigned this value.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([1, 2])
| >>> a.fill(0)
| >>> a
| array([0, 0])
| >>> a = np.empty(2)
| >>> a.fill(1)
| >>> a
| array([1., 1.])
|
| Fill expects a scalar value and always behaves the same as assigning
| to a single array element. The following is a rare example where this
| distinction is important:
|
| >>> a = np.array([None, None], dtype=object)
| >>> a[0] = np.array(3)
| >>> a
| array([array(3), None], dtype=object)
| >>> a.fill(np.array(3))
| >>> a
| array([array(3), array(3)], dtype=object)
|
| Where other forms of assignments will unpack the array being assigned:
|
| >>> a[...] = np.array(3)
| >>> a
| array([3, 3], dtype=object)
|
| flatten(...)
| a.flatten(order='C')
|
| Return a copy of the array collapsed into one dimension.
|
| Parameters
| ----------
| order : {'C', 'F', 'A', 'K'}, optional
| 'C' means to flatten in row-major (C-style) order.
| 'F' means to flatten in column-major (Fortran-
| style) order. 'A' means to flatten in column-major
| order if `a` is Fortran *contiguous* in memory,
| row-major order otherwise. 'K' means to flatten
| `a` in the order the elements occur in memory.
| The default is 'C'.
|
| Returns
| -------
| y : ndarray
| A copy of the input array, flattened to one dimension.
|
| See Also
| --------
| ravel : Return a flattened array.
| flat : A 1-D flat iterator over the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,2], [3,4]])
| >>> a.flatten()
| array([1, 2, 3, 4])
| >>> a.flatten('F')
| array([1, 3, 2, 4])
|
| getfield(...)
| a.getfield(dtype, offset=0)
|
| Returns a field of the given array as a certain type.
|
| A field is a view of the array data with a given data-type. The values in
| the view are determined by the given type and the offset into the current
| array in bytes. The offset needs to be such that the view dtype fits in the
| array dtype; for example an array of dtype complex128 has 16-byte elements.
| If taking a view with a 32-bit integer (4 bytes), the offset needs to be
| between 0 and 12 bytes.
|
| Parameters
| ----------
| dtype : str or dtype
| The data type of the view. The dtype size of the view can not be larger
| than that of the array itself.
| offset : int
| Number of bytes to skip before beginning the element view.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.diag([1.+1.j]*2)
| >>> x[1, 1] = 2 + 4.j
| >>> x
| array([[1.+1.j, 0.+0.j],
| [0.+0.j, 2.+4.j]])
| >>> x.getfield(np.float64)
| array([[1., 0.],
| [0., 2.]])
|
| By choosing an offset of 8 bytes we can select the complex part of the
| array for our view:
|
| >>> x.getfield(np.float64, offset=8)
| array([[1., 0.],
| [0., 4.]])
|
| item(...)
| a.item(*args)
|
| Copy an element of an array to a standard Python scalar and return it.
|
| Parameters
| ----------
| \*args : Arguments (variable number and type)
|
| * none: in this case, the method only works for arrays
| with one element (`a.size == 1`), which element is
| copied into a standard Python scalar object and returned.
|
| * int_type: this argument is interpreted as a flat index into
| the array, specifying which element to copy and return.
|
| * tuple of int_types: functions as does a single int_type argument,
| except that the argument is interpreted as an nd-index into the
| array.
|
| Returns
| -------
| z : Standard Python scalar object
| A copy of the specified element of the array as a suitable
| Python scalar
|
| Notes
| -----
| When the data type of `a` is longdouble or clongdouble, item() returns
| a scalar array object because there is no available Python scalar that
| would not lose information. Void arrays return a buffer object for item(),
| unless fields are defined, in which case a tuple is returned.
|
| `item` is very similar to a[args], except, instead of an array scalar,
| a standard Python scalar is returned. This can be useful for speeding up
| access to elements of the array and doing arithmetic on elements of the
| array using Python's optimized math.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.random.seed(123)
| >>> x = np.random.randint(9, size=(3, 3))
| >>> x
| array([[2, 2, 6],
| [1, 3, 6],
| [1, 0, 1]])
| >>> x.item(3)
| 1
| >>> x.item(7)
| 0
| >>> x.item((0, 1))
| 2
| >>> x.item((2, 2))
| 1
|
| For an array with object dtype, elements are returned as-is.
|
| >>> a = np.array([np.int64(1)], dtype=object)
| >>> a.item() #return np.int64
| np.int64(1)
|
| max(...)
| a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the maximum along a given axis.
|
| Refer to `numpy.amax` for full documentation.
|
| See Also
| --------
| numpy.amax : equivalent function
|
| mean(...)
| a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)
|
| Returns the average of the array elements along given axis.
|
| Refer to `numpy.mean` for full documentation.
|
| See Also
| --------
| numpy.mean : equivalent function
|
| min(...)
| a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Return the minimum along a given axis.
|
| Refer to `numpy.amin` for full documentation.
|
| See Also
| --------
| numpy.amin : equivalent function
|
| nonzero(...)
| a.nonzero()
|
| Return the indices of the elements that are non-zero.
|
| Refer to `numpy.nonzero` for full documentation.
|
| See Also
| --------
| numpy.nonzero : equivalent function
|
| partition(...)
| a.partition(kth, axis=-1, kind='introselect', order=None)
|
| Partially sorts the elements in the array 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. In the output array, all elements smaller than the k-th element
| are located to the left of this element and all equal or greater are
| located to its right. The ordering of the elements in the two partitions
| on the either side of the k-th element in the output array is undefined.
|
| .. versionadded:: 1.8.0
|
| Parameters
| ----------
| kth : int or sequence of ints
| Element index to partition by. The kth element value 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 kth it will partition all elements
| indexed by kth of them into their sorted position at once.
|
| .. deprecated:: 1.22.0
| Passing booleans as index is deprecated.
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'introselect'}, optional
| Selection algorithm. Default is 'introselect'.
| order : str 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, and not all fields need to be specified,
| but unspecified fields will still be used, in the order in which
| they come up in the dtype, to break ties.
|
| See Also
| --------
| numpy.partition : Return a partitioned copy of an array.
| argpartition : Indirect partition.
| sort : Full sort.
|
| Notes
| -----
| See ``np.partition`` for notes on the different algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([3, 4, 2, 1])
| >>> a.partition(3)
| >>> a
| array([2, 1, 3, 4]) # may vary
|
| >>> a.partition((1, 3))
| >>> a
| array([1, 2, 3, 4])
|
| prod(...)
| a.prod(axis=None, dtype=None, out=None, keepdims=False,
| initial=1, where=True)
|
| Return the product of the array elements over the given axis
|
| Refer to `numpy.prod` for full documentation.
|
| See Also
| --------
| numpy.prod : equivalent function
|
| put(...)
| a.put(indices, values, mode='raise')
|
| Set ``a.flat[n] = values[n]`` for all `n` in indices.
|
| Refer to `numpy.put` for full documentation.
|
| See Also
| --------
| numpy.put : equivalent function
|
| ravel(...)
| a.ravel([order])
|
| Return a flattened array.
|
| Refer to `numpy.ravel` for full documentation.
|
| See Also
| --------
| numpy.ravel : equivalent function
|
| ndarray.flat : a flat iterator on the array.
|
| repeat(...)
| a.repeat(repeats, axis=None)
|
| Repeat elements of an array.
|
| Refer to `numpy.repeat` for full documentation.
|
| See Also
| --------
| numpy.repeat : equivalent function
|
| reshape(...)
| a.reshape(shape, /, *, order='C', copy=None)
|
| Returns an array containing the same data with a new shape.
|
| Refer to `numpy.reshape` for full documentation.
|
| See Also
| --------
| numpy.reshape : equivalent function
|
| Notes
| -----
| Unlike the free function `numpy.reshape`, this method on `ndarray` allows
| the elements of the shape parameter to be passed in as separate arguments.
| For example, ``a.reshape(10, 11)`` is equivalent to
| ``a.reshape((10, 11))``.
|
| resize(...)
| a.resize(new_shape, refcheck=True)
|
| Change shape and size of array in-place.
|
| Parameters
| ----------
| new_shape : tuple of ints, or `n` ints
| Shape of resized array.
| refcheck : bool, optional
| If False, reference count will not be checked. Default is True.
|
| Returns
| -------
| None
|
| Raises
| ------
| ValueError
| If `a` does not own its own data or references or views to it exist,
| and the data memory must be changed.
| PyPy only: will always raise if the data memory must be changed, since
| there is no reliable way to determine if references or views to it
| exist.
|
| SystemError
| If the `order` keyword argument is specified. This behaviour is a
| bug in NumPy.
|
| See Also
| --------
| resize : Return a new array with the specified shape.
|
| Notes
| -----
| This reallocates space for the data area if necessary.
|
| Only contiguous arrays (data elements consecutive in memory) can be
| resized.
|
| The purpose of the reference count check is to make sure you
| do not use this array as a buffer for another Python object and then
| reallocate the memory. However, reference counts can increase in
| other ways so if you are sure that you have not shared the memory
| for this array with another Python object, then you may safely set
| `refcheck` to False.
|
| Examples
| --------
| Shrinking an array: array is flattened (in the order that the data are
| stored in memory), resized, and reshaped:
|
| >>> import numpy as np
|
| >>> a = np.array([[0, 1], [2, 3]], order='C')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [1]])
|
| >>> a = np.array([[0, 1], [2, 3]], order='F')
| >>> a.resize((2, 1))
| >>> a
| array([[0],
| [2]])
|
| Enlarging an array: as above, but missing entries are filled with zeros:
|
| >>> b = np.array([[0, 1], [2, 3]])
| >>> b.resize(2, 3) # new_shape parameter doesn't have to be a tuple
| >>> b
| array([[0, 1, 2],
| [3, 0, 0]])
|
| Referencing an array prevents resizing...
|
| >>> c = a
| >>> a.resize((1, 1))
| Traceback (most recent call last):
| ...
| ValueError: cannot resize an array that references or is referenced ...
|
| Unless `refcheck` is False:
|
| >>> a.resize((1, 1), refcheck=False)
| >>> a
| array([[0]])
| >>> c
| array([[0]])
|
| round(...)
| a.round(decimals=0, out=None)
|
| Return `a` with each element rounded to the given number of decimals.
|
| Refer to `numpy.around` for full documentation.
|
| See Also
| --------
| numpy.around : equivalent function
|
| searchsorted(...)
| a.searchsorted(v, side='left', sorter=None)
|
| Find indices where elements of v should be inserted in a to maintain order.
|
| For full documentation, see `numpy.searchsorted`
|
| See Also
| --------
| numpy.searchsorted : equivalent function
|
| setfield(...)
| a.setfield(val, dtype, offset=0)
|
| Put a value into a specified place in a field defined by a data-type.
|
| Place `val` into `a`'s field defined by `dtype` and beginning `offset`
| bytes into the field.
|
| Parameters
| ----------
| val : object
| Value to be placed in field.
| dtype : dtype object
| Data-type of the field in which to place `val`.
| offset : int, optional
| The number of bytes into the field at which to place `val`.
|
| Returns
| -------
| None
|
| See Also
| --------
| getfield
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.eye(3)
| >>> x.getfield(np.float64)
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
| >>> x.setfield(3, np.int32)
| >>> x.getfield(np.int32)
| array([[3, 3, 3],
| [3, 3, 3],
| [3, 3, 3]], dtype=int32)
| >>> x
| array([[1.0e+000, 1.5e-323, 1.5e-323],
| [1.5e-323, 1.0e+000, 1.5e-323],
| [1.5e-323, 1.5e-323, 1.0e+000]])
| >>> x.setfield(np.eye(3), np.int32)
| >>> x
| array([[1., 0., 0.],
| [0., 1., 0.],
| [0., 0., 1.]])
|
| setflags(...)
| a.setflags(write=None, align=None, uic=None)
|
| Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY,
| respectively.
|
| These Boolean-valued flags affect how numpy interprets the memory
| area used by `a` (see Notes below). The ALIGNED flag can only
| be set to True if the data is actually aligned according to the type.
| The WRITEBACKIFCOPY flag can never be set
| to True. The flag WRITEABLE can only be set to True if the array owns its
| own memory, or the ultimate owner of the memory exposes a writeable buffer
| interface, or is a string. (The exception for string is made so that
| unpickling can be done without copying memory.)
|
| Parameters
| ----------
| write : bool, optional
| Describes whether or not `a` can be written to.
| align : bool, optional
| Describes whether or not `a` is aligned properly for its type.
| uic : bool, optional
| Describes whether or not `a` is a copy of another "base" array.
|
| Notes
| -----
| Array flags provide information about how the memory area used
| for the array is to be interpreted. There are 7 Boolean flags
| in use, only three of which can be changed by the user:
| WRITEBACKIFCOPY, WRITEABLE, and ALIGNED.
|
| WRITEABLE (W) the data area can be written to;
|
| ALIGNED (A) the data and strides are aligned appropriately for the hardware
| (as determined by the compiler);
|
| WRITEBACKIFCOPY (X) this array is a copy of some other array (referenced
| by .base). When the C-API function PyArray_ResolveWritebackIfCopy is
| called, the base array will be updated with the contents of this array.
|
| All flags can be accessed using the single (upper case) letter as well
| as the full name.
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.array([[3, 1, 7],
| ... [2, 0, 0],
| ... [8, 5, 9]])
| >>> y
| array([[3, 1, 7],
| [2, 0, 0],
| [8, 5, 9]])
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : True
| ALIGNED : True
| WRITEBACKIFCOPY : False
| >>> y.setflags(write=0, align=0)
| >>> y.flags
| C_CONTIGUOUS : True
| F_CONTIGUOUS : False
| OWNDATA : True
| WRITEABLE : False
| ALIGNED : False
| WRITEBACKIFCOPY : False
| >>> y.setflags(uic=1)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: cannot set WRITEBACKIFCOPY flag to True
|
| sort(...)
| a.sort(axis=-1, kind=None, order=None)
|
| Sort an array in-place. Refer to `numpy.sort` for full documentation.
|
| Parameters
| ----------
| axis : int, optional
| Axis along which to sort. Default is -1, which means sort along the
| last axis.
| kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
| Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
| and 'mergesort' use timsort under the covers and, in general, the
| actual implementation will vary with datatype. The 'mergesort' option
| is retained for backwards compatibility.
|
| .. versionchanged:: 1.15.0
| The 'stable' option was added.
|
| order : str 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, and 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.
|
| See Also
| --------
| numpy.sort : Return a sorted copy of an array.
| numpy.argsort : Indirect sort.
| numpy.lexsort : Indirect stable sort on multiple keys.
| numpy.searchsorted : Find elements in sorted array.
| numpy.partition: Partial sort.
|
| Notes
| -----
| See `numpy.sort` for notes on the different sorting algorithms.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1,4], [3,1]])
| >>> a.sort(axis=1)
| >>> a
| array([[1, 4],
| [1, 3]])
| >>> a.sort(axis=0)
| >>> a
| array([[1, 3],
| [1, 4]])
|
| Use the `order` keyword to specify a field to use when sorting a
| structured array:
|
| >>> a = np.array([('a', 2), ('c', 1)], dtype=[('x', 'S1'), ('y', int)])
| >>> a.sort(order='y')
| >>> a
| array([(b'c', 1), (b'a', 2)],
| dtype=[('x', 'S1'), ('y', '<i8')])
|
| squeeze(...)
| a.squeeze(axis=None)
|
| Remove axes of length one from `a`.
|
| Refer to `numpy.squeeze` for full documentation.
|
| See Also
| --------
| numpy.squeeze : equivalent function
|
| std(...)
| a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the standard deviation of the array elements along given axis.
|
| Refer to `numpy.std` for full documentation.
|
| See Also
| --------
| numpy.std : equivalent function
|
| sum(...)
| a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)
|
| Return the sum of the array elements over the given axis.
|
| Refer to `numpy.sum` for full documentation.
|
| See Also
| --------
| numpy.sum : equivalent function
|
| swapaxes(...)
| a.swapaxes(axis1, axis2)
|
| Return a view of the array with `axis1` and `axis2` interchanged.
|
| Refer to `numpy.swapaxes` for full documentation.
|
| See Also
| --------
| numpy.swapaxes : equivalent function
|
| take(...)
| a.take(indices, axis=None, out=None, mode='raise')
|
| Return an array formed from the elements of `a` at the given indices.
|
| Refer to `numpy.take` for full documentation.
|
| See Also
| --------
| numpy.take : equivalent function
|
| to_device(...)
|
| tobytes(...)
| a.tobytes(order='C')
|
| Construct Python bytes containing the raw data bytes in the array.
|
| Constructs Python bytes showing a copy of the raw contents of
| data memory. The bytes object is produced in C-order by default.
| This behavior is controlled by the ``order`` parameter.
|
| .. versionadded:: 1.9.0
|
| Parameters
| ----------
| order : {'C', 'F', 'A'}, optional
| Controls the memory layout of the bytes object. 'C' means C-order,
| 'F' means F-order, 'A' (short for *Any*) means 'F' if `a` is
| Fortran contiguous, 'C' otherwise. Default is 'C'.
|
| Returns
| -------
| s : bytes
| Python bytes exhibiting a copy of `a`'s raw data.
|
| See also
| --------
| frombuffer
| Inverse of this operation, construct a 1-dimensional array from Python
| bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([[0, 1], [2, 3]], dtype='<u2')
| >>> x.tobytes()
| b'\x00\x00\x01\x00\x02\x00\x03\x00'
| >>> x.tobytes('C') == x.tobytes()
| True
| >>> x.tobytes('F')
| b'\x00\x00\x02\x00\x01\x00\x03\x00'
|
| tofile(...)
| a.tofile(fid, sep="", format="%s")
|
| Write array to a file as text or binary (default).
|
| Data is always written in 'C' order, independent of the order of `a`.
| The data produced by this method can be recovered using the function
| fromfile().
|
| Parameters
| ----------
| fid : file or str or Path
| An open file object, or a string containing a filename.
|
| .. versionchanged:: 1.17.0
| `pathlib.Path` objects are now accepted.
|
| sep : str
| Separator between array items for text output.
| If "" (empty), a binary file is written, equivalent to
| ``file.write(a.tobytes())``.
| format : str
| Format string for text file output.
| Each entry in the array is formatted to text by first converting
| it to the closest Python type, and then using "format" % item.
|
| Notes
| -----
| This is a convenience function for quick storage of array data.
| Information on endianness and precision is lost, so this method is not a
| good choice for files intended to archive data or transport data between
| machines with different endianness. Some of these problems can be overcome
| by outputting the data as text files, at the expense of speed and file
| size.
|
| When fid is a file object, array contents are directly written to the
| file, bypassing the file object's ``write`` method. As a result, tofile
| cannot be used with files objects supporting compression (e.g., GzipFile)
| or file-like objects that do not support ``fileno()`` (e.g., BytesIO).
|
| tolist(...)
| a.tolist()
|
| Return the array as an ``a.ndim``-levels deep nested list of Python scalars.
|
| Return a copy of the array data as a (nested) Python list.
| Data items are converted to the nearest compatible builtin Python type, via
| the `~numpy.ndarray.item` function.
|
| If ``a.ndim`` is 0, then since the depth of the nested list is 0, it will
| not be a list at all, but a simple Python scalar.
|
| Parameters
| ----------
| none
|
| Returns
| -------
| y : object, or list of object, or list of list of object, or ...
| The possibly nested list of array elements.
|
| Notes
| -----
| The array may be recreated via ``a = np.array(a.tolist())``, although this
| may sometimes lose precision.
|
| Examples
| --------
| For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
| except that ``tolist`` changes numpy scalars to Python scalars:
|
| >>> import numpy as np
| >>> a = np.uint32([1, 2])
| >>> a_list = list(a)
| >>> a_list
| [1, 2]
| >>> type(a_list[0])
| <class 'numpy.uint32'>
| >>> a_tolist = a.tolist()
| >>> a_tolist
| [1, 2]
| >>> type(a_tolist[0])
| <class 'int'>
|
| Additionally, for a 2D array, ``tolist`` applies recursively:
|
| >>> a = np.array([[1, 2], [3, 4]])
| >>> list(a)
| [array([1, 2]), array([3, 4])]
| >>> a.tolist()
| [[1, 2], [3, 4]]
|
| The base case for this recursion is a 0D array:
|
| >>> a = np.array(1)
| >>> list(a)
| Traceback (most recent call last):
| ...
| TypeError: iteration over a 0-d array
| >>> a.tolist()
| 1
|
| tostring(...)
| a.tostring(order='C')
|
| A compatibility alias for `~ndarray.tobytes`, with exactly the same
| behavior.
|
| Despite its name, it returns :class:`bytes` not :class:`str`\ s.
|
| .. deprecated:: 1.19.0
|
| trace(...)
| a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
|
| Return the sum along diagonals of the array.
|
| Refer to `numpy.trace` for full documentation.
|
| See Also
| --------
| numpy.trace : equivalent function
|
| transpose(...)
| a.transpose(*axes)
|
| Returns a view of the array with axes transposed.
|
| Refer to `numpy.transpose` for full documentation.
|
| Parameters
| ----------
| axes : None, tuple of ints, or `n` ints
|
| * None or no argument: reverses the order of the axes.
|
| * tuple of ints: `i` in the `j`-th place in the tuple means that the
| array's `i`-th axis becomes the transposed array's `j`-th axis.
|
| * `n` ints: same as an n-tuple of the same ints (this form is
| intended simply as a "convenience" alternative to the tuple form).
|
| Returns
| -------
| p : ndarray
| View of the array with its axes suitably permuted.
|
| See Also
| --------
| transpose : Equivalent function.
| ndarray.T : Array property returning the array transposed.
| ndarray.reshape : Give a new shape to an array without changing its data.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.transpose()
| array([[1, 3],
| [2, 4]])
| >>> a.transpose((1, 0))
| array([[1, 3],
| [2, 4]])
| >>> a.transpose(1, 0)
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.transpose()
| array([1, 2, 3, 4])
|
| var(...)
| a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)
|
| Returns the variance of the array elements, along given axis.
|
| Refer to `numpy.var` for full documentation.
|
| See Also
| --------
| numpy.var : equivalent function
|
| view(...)
| a.view([dtype][, type])
|
| New view of array with the same data.
|
| .. note::
| Passing None for ``dtype`` is different from omitting the parameter,
| since the former invokes ``dtype(None)`` which is an alias for
| ``dtype('float64')``.
|
| Parameters
| ----------
| dtype : data-type or ndarray sub-class, optional
| Data-type descriptor of the returned view, e.g., float32 or int16.
| Omitting it results in the view having the same data-type as `a`.
| This argument can also be specified as an ndarray sub-class, which
| then specifies the type of the returned object (this is equivalent to
| setting the ``type`` parameter).
| type : Python type, optional
| Type of the returned view, e.g., ndarray or matrix. Again, omission
| of the parameter results in type preservation.
|
| Notes
| -----
| ``a.view()`` is used two different ways:
|
| ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
| of the array's memory with a different data-type. This can cause a
| reinterpretation of the bytes of memory.
|
| ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
| returns an instance of `ndarray_subclass` that looks at the same array
| (same shape, dtype, etc.) This does not cause a reinterpretation of the
| memory.
|
| For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
| bytes per entry than the previous dtype (for example, converting a regular
| array to a structured array), then the last axis of ``a`` must be
| contiguous. This axis will be resized in the result.
|
| .. versionchanged:: 1.23.0
| Only the last axis needs to be contiguous. Previously, the entire array
| had to be C-contiguous.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
|
| Viewing array data using a different type and dtype:
|
| >>> nonneg = np.dtype([("a", np.uint8), ("b", np.uint8)])
| >>> y = x.view(dtype=nonneg, type=np.recarray)
| >>> x["a"]
| array([-1], dtype=int8)
| >>> y.a
| array([255], dtype=uint8)
|
| Creating a view on a structured array so it can be used in calculations
|
| >>> x = np.array([(1, 2),(3,4)], dtype=[('a', np.int8), ('b', np.int8)])
| >>> xv = x.view(dtype=np.int8).reshape(-1,2)
| >>> xv
| array([[1, 2],
| [3, 4]], dtype=int8)
| >>> xv.mean(0)
| array([2., 3.])
|
| Making changes to the view changes the underlying array
|
| >>> xv[0,1] = 20
| >>> x
| array([(1, 20), (3, 4)], dtype=[('a', 'i1'), ('b', 'i1')])
|
| Using a view to convert an array to a recarray:
|
| >>> z = x.view(np.recarray)
| >>> z.a
| array([1, 3], dtype=int8)
|
| Views share data:
|
| >>> x[0] = (9, 10)
| >>> z[0]
| np.record((9, 10), dtype=[('a', 'i1'), ('b', 'i1')])
|
| Views that change the dtype size (bytes per entry) should normally be
| avoided on arrays defined by slices, transposes, fortran-ordering, etc.:
|
| >>> x = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int16)
| >>> y = x[:, ::2]
| >>> y
| array([[1, 3],
| [4, 6]], dtype=int16)
| >>> y.view(dtype=[('width', np.int16), ('length', np.int16)])
| Traceback (most recent call last):
| ...
| ValueError: To change to a dtype of a different size, the last axis must be contiguous
| >>> z = y.copy()
| >>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
| array([[(1, 3)],
| [(4, 6)]], dtype=[('width', '<i2'), ('length', '<i2')])
|
| However, views that change dtype are totally fine for arrays with a
| contiguous last axis, even if the rest of the axes are not C-contiguous:
|
| >>> x = np.arange(2 * 3 * 4, dtype=np.int8).reshape(2, 3, 4)
| >>> x.transpose(1, 0, 2).view(np.int16)
| array([[[ 256, 770],
| [3340, 3854]],
| <BLANKLINE>
| [[1284, 1798],
| [4368, 4882]],
| <BLANKLINE>
| [[2312, 2826],
| [5396, 5910]]], dtype=int16)
|
| ----------------------------------------------------------------------
| Class methods inherited from numpy.ndarray:
|
| __class_getitem__(...)
| a.__class_getitem__(item, /)
|
| Return a parametrized wrapper around the `~numpy.ndarray` type.
|
| .. versionadded:: 1.22
|
| Returns
| -------
| alias : types.GenericAlias
| A parametrized `~numpy.ndarray` type.
|
| Examples
| --------
| >>> from typing import Any
| >>> import numpy as np
|
| >>> np.ndarray[Any, np.dtype[Any]]
| numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
|
| See Also
| --------
| :pep:`585` : Type hinting generics in standard collections.
| numpy.typing.NDArray : An ndarray alias :term:`generic <generic type>`
| w.r.t. its `dtype.type <numpy.dtype.type>`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from numpy.ndarray:
|
| T
| View of the transposed array.
|
| Same as ``self.transpose()``.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.T
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.array([1, 2, 3, 4])
| >>> a
| array([1, 2, 3, 4])
| >>> a.T
| array([1, 2, 3, 4])
|
| See Also
| --------
| transpose
|
| __array_interface__
| Array protocol: Python side.
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: C-struct side.
|
| base
| Base object if memory is from some other object.
|
| Examples
| --------
| The base of an array that owns its memory is None:
|
| >>> import numpy as np
| >>> x = np.array([1,2,3,4])
| >>> x.base is None
| True
|
| Slicing creates a view, whose memory is shared with x:
|
| >>> y = x[2:]
| >>> y.base is x
| True
|
| ctypes
| An object to simplify the interaction of the array with the ctypes
| module.
|
| This attribute creates an object that makes it easier to use arrays
| when calling shared libraries with the ctypes module. The returned
| object has, among others, data, shape, and strides attributes (see
| Notes below) which themselves return ctypes objects that can be used
| as arguments to a shared library.
|
| Parameters
| ----------
| None
|
| Returns
| -------
| c : Python object
| Possessing attributes data, shape, strides, etc.
|
| See Also
| --------
| numpy.ctypeslib
|
| Notes
| -----
| Below are the public attributes of this object which were documented
| in "Guide to NumPy" (we have omitted undocumented public attributes,
| as well as documented private attributes):
|
| .. autoattribute:: numpy._core._internal._ctypes.data
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.shape
| :noindex:
|
| .. autoattribute:: numpy._core._internal._ctypes.strides
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.data_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.shape_as
| :noindex:
|
| .. automethod:: numpy._core._internal._ctypes.strides_as
| :noindex:
|
| If the ctypes module is not available, then the ctypes attribute
| of array objects still returns something useful, but ctypes objects
| are not returned and errors may be raised instead. In particular,
| the object will still have the ``as_parameter`` attribute which will
| return an integer equal to the data attribute.
|
| Examples
| --------
| >>> import numpy as np
| >>> import ctypes
| >>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
| >>> x
| array([[0, 1],
| [2, 3]], dtype=int32)
| >>> x.ctypes.data
| 31962608 # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))
| <__main__.LP_c_uint object at 0x7ff2fc1fc200> # may vary
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32)).contents
| c_uint(0)
| >>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_uint64)).contents
| c_ulong(4294967296)
| >>> x.ctypes.shape
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1fce60> # may vary
| >>> x.ctypes.strides
| <numpy._core._internal.c_long_Array_2 object at 0x7ff2fc1ff320> # may vary
|
| data
| Python buffer object pointing to the start of the array's data.
|
| device
|
| dtype
| Data-type of the array's elements.
|
| .. warning::
|
| Setting ``arr.dtype`` is discouraged and may be deprecated in the
| future. Setting will replace the ``dtype`` without modifying the
| memory (see also `ndarray.view` and `ndarray.astype`).
|
| Parameters
| ----------
| None
|
| Returns
| -------
| d : numpy dtype object
|
| See Also
| --------
| ndarray.astype : Cast the values contained in the array to a new data-type.
| ndarray.view : Create a view of the same data but a different data-type.
| numpy.dtype
|
| Examples
| --------
| >>> x
| array([[0, 1],
| [2, 3]])
| >>> x.dtype
| dtype('int32')
| >>> type(x.dtype)
| <type 'numpy.dtype'>
|
| flags
| Information about the memory layout of the array.
|
| Attributes
| ----------
| C_CONTIGUOUS (C)
| The data is in a single, C-style contiguous segment.
| F_CONTIGUOUS (F)
| The data is in a single, Fortran-style contiguous segment.
| OWNDATA (O)
| The array owns the memory it uses or borrows it from another object.
| WRITEABLE (W)
| The data area can be written to. Setting this to False locks
| the data, making it read-only. A view (slice, etc.) inherits WRITEABLE
| from its base array at creation time, but a view of a writeable
| array may be subsequently locked while the base array remains writeable.
| (The opposite is not true, in that a view of a locked array may not
| be made writeable. However, currently, locking a base object does not
| lock any views that already reference it, so under that circumstance it
| is possible to alter the contents of a locked array via a previously
| created writeable view onto it.) Attempting to change a non-writeable
| array raises a RuntimeError exception.
| ALIGNED (A)
| The data and all elements are aligned appropriately for the hardware.
| WRITEBACKIFCOPY (X)
| This array is a copy of some other array. The C-API function
| PyArray_ResolveWritebackIfCopy must be called before deallocating
| to the base array will be updated with the contents of this array.
| FNC
| F_CONTIGUOUS and not C_CONTIGUOUS.
| FORC
| F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
| BEHAVED (B)
| ALIGNED and WRITEABLE.
| CARRAY (CA)
| BEHAVED and C_CONTIGUOUS.
| FARRAY (FA)
| BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
|
| Notes
| -----
| The `flags` object can be accessed dictionary-like (as in ``a.flags['WRITEABLE']``),
| or by using lowercased attribute names (as in ``a.flags.writeable``). Short flag
| names are only supported in dictionary access.
|
| Only the WRITEBACKIFCOPY, WRITEABLE, and ALIGNED flags can be
| changed by the user, via direct assignment to the attribute or dictionary
| entry, or by calling `ndarray.setflags`.
|
| The array flags cannot be set arbitrarily:
|
| - WRITEBACKIFCOPY can only be set ``False``.
| - ALIGNED can only be set ``True`` if the data is truly aligned.
| - WRITEABLE can only be set ``True`` if the array owns its own memory
| or the ultimate owner of the memory exposes a writeable buffer
| interface or is a string.
|
| Arrays can be both C-style and Fortran-style contiguous simultaneously.
| This is clear for 1-dimensional arrays, but can also be true for higher
| dimensional arrays.
|
| Even for contiguous arrays a stride for a given dimension
| ``arr.strides[dim]`` may be *arbitrary* if ``arr.shape[dim] == 1``
| or the array has no elements.
| It does *not* generally hold that ``self.strides[-1] == self.itemsize``
| for C-style contiguous arrays or ``self.strides[0] == self.itemsize`` for
| Fortran-style contiguous arrays is true.
|
| flat
| A 1-D iterator over the array.
|
| This is a `numpy.flatiter` instance, which acts similarly to, but is not
| a subclass of, Python's built-in iterator object.
|
| See Also
| --------
| flatten : Return a copy of the array collapsed into one dimension.
|
| flatiter
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.arange(1, 7).reshape(2, 3)
| >>> x
| array([[1, 2, 3],
| [4, 5, 6]])
| >>> x.flat[3]
| 4
| >>> x.T
| array([[1, 4],
| [2, 5],
| [3, 6]])
| >>> x.T.flat[3]
| 5
| >>> type(x.flat)
| <class 'numpy.flatiter'>
|
| An assignment example:
|
| >>> x.flat = 3; x
| array([[3, 3, 3],
| [3, 3, 3]])
| >>> x.flat[[1,4]] = 1; x
| array([[3, 1, 3],
| [3, 1, 3]])
|
| imag
| The imaginary part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.imag
| array([ 0. , 0.70710678])
| >>> x.imag.dtype
| dtype('float64')
|
| itemset
|
| itemsize
| Length of one array element in bytes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1,2,3], dtype=np.float64)
| >>> x.itemsize
| 8
| >>> x = np.array([1,2,3], dtype=np.complex128)
| >>> x.itemsize
| 16
|
| mT
| View of the matrix transposed array.
|
| The matrix transpose is the transpose of the last two dimensions, even
| if the array is of higher dimension.
|
| .. versionadded:: 2.0
|
| Raises
| ------
| ValueError
| If the array is of dimension less than 2.
|
| Examples
| --------
| >>> import numpy as np
| >>> a = np.array([[1, 2], [3, 4]])
| >>> a
| array([[1, 2],
| [3, 4]])
| >>> a.mT
| array([[1, 3],
| [2, 4]])
|
| >>> a = np.arange(8).reshape((2, 2, 2))
| >>> a
| array([[[0, 1],
| [2, 3]],
| <BLANKLINE>
| [[4, 5],
| [6, 7]]])
| >>> a.mT
| array([[[0, 2],
| [1, 3]],
| <BLANKLINE>
| [[4, 6],
| [5, 7]]])
|
| nbytes
| Total bytes consumed by the elements of the array.
|
| Notes
| -----
| Does not include memory consumed by non-element attributes of the
| array object.
|
| See Also
| --------
| sys.getsizeof
| Memory consumed by the object itself without parents in case view.
| This does include memory consumed by non-element attributes.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3,5,2), dtype=np.complex128)
| >>> x.nbytes
| 480
| >>> np.prod(x.shape) * x.itemsize
| 480
|
| ndim
| Number of array dimensions.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3])
| >>> x.ndim
| 1
| >>> y = np.zeros((2, 3, 4))
| >>> y.ndim
| 3
|
| newbyteorder
|
| ptp
|
| real
| The real part of the array.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.sqrt([1+0j, 0+1j])
| >>> x.real
| array([ 1. , 0.70710678])
| >>> x.real.dtype
| dtype('float64')
|
| See Also
| --------
| numpy.real : equivalent function
|
| shape
| Tuple of array dimensions.
|
| The shape property is usually used to get the current shape of an array,
| but may also be used to reshape the array in-place by assigning a tuple of
| array dimensions to it. As with `numpy.reshape`, one of the new shape
| dimensions can be -1, in which case its value is inferred from the size of
| the array and the remaining dimensions. Reshaping an array in-place will
| fail if a copy is required.
|
| .. warning::
|
| Setting ``arr.shape`` is discouraged and may be deprecated in the
| future. Using `ndarray.reshape` is the preferred approach.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.array([1, 2, 3, 4])
| >>> x.shape
| (4,)
| >>> y = np.zeros((2, 3, 4))
| >>> y.shape
| (2, 3, 4)
| >>> y.shape = (3, 8)
| >>> y
| array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.],
| [ 0., 0., 0., 0., 0., 0., 0., 0.]])
| >>> y.shape = (3, 6)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ValueError: total size of new array must be unchanged
| >>> np.zeros((4,2))[::2].shape = (-1,)
| Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| AttributeError: Incompatible shape for in-place modification. Use
| `.reshape()` to make a copy with the desired shape.
|
| See Also
| --------
| numpy.shape : Equivalent getter function.
| numpy.reshape : Function similar to setting ``shape``.
| ndarray.reshape : Method similar to setting ``shape``.
|
| size
| Number of elements in the array.
|
| Equal to ``np.prod(a.shape)``, i.e., the product of the array's
| dimensions.
|
| Notes
| -----
| `a.size` returns a standard arbitrary precision Python integer. This
| may not be the case with other methods of obtaining the same value
| (like the suggested ``np.prod(a.shape)``, which returns an instance
| of ``np.int_``), and may be relevant if the value is used further in
| calculations that may overflow a fixed size integer type.
|
| Examples
| --------
| >>> import numpy as np
| >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
| >>> x.size
| 30
| >>> np.prod(x.shape)
| 30
|
| strides
| Tuple of bytes to step in each dimension when traversing an array.
|
| The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
| is::
|
| offset = sum(np.array(i) * a.strides)
|
| A more detailed explanation of strides can be found in
| :ref:`arrays.ndarray`.
|
| .. warning::
|
| Setting ``arr.strides`` is discouraged and may be deprecated in the
| future. `numpy.lib.stride_tricks.as_strided` should be preferred
| to create a new view of the same data in a safer way.
|
| Notes
| -----
| Imagine an array of 32-bit integers (each 4 bytes)::
|
| x = np.array([[0, 1, 2, 3, 4],
| [5, 6, 7, 8, 9]], dtype=np.int32)
|
| This array is stored in memory as 40 bytes, one after the other
| (known as a contiguous block of memory). The strides of an array tell
| us how many bytes we have to skip in memory to move to the next position
| along a certain axis. For example, we have to skip 4 bytes (1 value) to
| move to the next column, but 20 bytes (5 values) to get to the same
| position in the next row. As such, the strides for the array `x` will be
| ``(20, 4)``.
|
| See Also
| --------
| numpy.lib.stride_tricks.as_strided
|
| Examples
| --------
| >>> import numpy as np
| >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
| >>> y
| array([[[ 0, 1, 2, 3],
| [ 4, 5, 6, 7],
| [ 8, 9, 10, 11]],
| [[12, 13, 14, 15],
| [16, 17, 18, 19],
| [20, 21, 22, 23]]])
| >>> y.strides
| (48, 16, 4)
| >>> y[1,1,1]
| 17
| >>> offset=sum(y.strides * np.array((1,1,1)))
| >>> offset/y.itemsize
| 17
|
| >>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
| >>> x.strides
| (32, 4, 224, 1344)
| >>> i = np.array([3,5,2,2])
| >>> offset = sum(i * x.strides)
| >>> x[3,5,2,2]
| 813
| >>> offset / x.itemsize
| 813
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from numpy.ndarray:
|
| __hash__ = None
numpy.reciprocal
Python Library Documentation: ufunc
reciprocal = <ufunc 'reciprocal'>
reciprocal(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the reciprocal of the argument, element-wise.
Calculates ``1/x``.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Return array.
This is a scalar if `x` is a scalar.
Notes
-----
.. note::
This function is not designed to work with integers.
For integer arguments with absolute value larger than 1 the result is
always zero because of the way Python handles integer division. For
integer zero the result is an overflow.
Examples
--------
>>> import numpy as np
>>> np.reciprocal(2.)
0.5
>>> np.reciprocal([1, 2., 3.33])
array([ 1. , 0.5 , 0.3003003])
numpy.record
Python Library Documentation: class record in module numpy class record(void) | A data-type scalar that allows field access as attribute lookup. | | Method resolution order: | record | void | flexible | generic | builtins.object | | Methods defined here: | | __getattribute__(self, attr) from numpy._core.records.record | Return getattr(self, name). | | __getitem__(self, indx) from numpy._core.records.record | Return self[key]. | | __repr__(self) from numpy._core.records.record | Return repr(self). | | __setattr__(self, attr, val) from numpy._core.records.record | Implement setattr(self, name, value). | | __str__(self) from numpy._core.records.record | Return str(self). | | pprint(self) from numpy._core.records.record | Pretty-print all fields. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from void: | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __setitem__(self, key, value, /) | Set self[key] to value. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | ---------------------------------------------------------------------- | Static methods inherited from void: | | __new__(*args, **kwargs) class method of numpy.void | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors inherited from void: | | base | base object | | dtype | dtype object | | flags | integer value of flags | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | data | Pointer to start of data. | | device | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.remainder
Python Library Documentation: ufunc
remainder = <ufunc 'remainder'>
remainder(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns the element-wise remainder of division.
Computes the remainder complementary to the `floor_divide` function. It is
equivalent to the Python modulus operator ``x1 % x2`` and has the same sign
as the divisor `x2`. The MATLAB function equivalent to ``np.remainder``
is ``mod``.
.. warning::
This should not be confused with:
* Python 3.7's `math.remainder` and C's ``remainder``, which
computes the IEEE remainder, which are the complement to
``round(x1 / x2)``.
* The MATLAB ``rem`` function and or the C ``%`` operator which is the
complement to ``int(x1 / x2)``.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The element-wise remainder of the quotient ``floor_divide(x1, x2)``.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
floor_divide : Equivalent of Python ``//`` operator.
divmod : Simultaneous floor division and remainder.
fmod : Equivalent of the MATLAB ``rem`` function.
divide, floor
Notes
-----
Returns 0 when `x2` is 0 and both `x1` and `x2` are (arrays of)
integers.
``mod`` is an alias of ``remainder``.
Examples
--------
>>> import numpy as np
>>> np.remainder([4, 7], [2, 3])
array([0, 1])
>>> np.remainder(np.arange(7), 5)
array([0, 1, 2, 3, 4, 0, 1])
The ``%`` operator can be used as a shorthand for ``np.remainder`` on
ndarrays.
>>> x1 = np.arange(7)
>>> x1 % 5
array([0, 1, 2, 3, 4, 0, 1])
numpy.repeat
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
repeat(a, repeats, axis=None)
Repeat each element of an array after themselves
Parameters
----------
a : array_like
Input array.
repeats : int or array of ints
The number of repetitions for each element. `repeats` is broadcasted
to fit the shape of the given axis.
axis : int, optional
The axis along which to repeat values. By default, use the
flattened input array, and return a flat output array.
Returns
-------
repeated_array : ndarray
Output array which has the same shape as `a`, except along
the given axis.
See Also
--------
tile : Tile an array.
unique : Find the unique elements of an array.
Examples
--------
>>> import numpy as np
>>> np.repeat(3, 4)
array([3, 3, 3, 3])
>>> x = np.array([[1,2],[3,4]])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
>>> np.repeat(x, 3, axis=1)
array([[1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4]])
>>> np.repeat(x, [1, 2], axis=0)
array([[1, 2],
[3, 4],
[3, 4]])
numpy.require
Python Library Documentation: function require in module numpy
require(a, dtype=None, requirements=None, *, like=None)
Return an ndarray of the provided type that satisfies requirements.
This function is useful to be sure that an array with the correct flags
is returned for passing to compiled code (perhaps through ctypes).
Parameters
----------
a : array_like
The object to be converted to a type-and-requirement-satisfying array.
dtype : data-type
The required data-type. If None preserve the current dtype. If your
application requires the data to be in native byteorder, include
a byteorder specification as a part of the dtype specification.
requirements : str or sequence of str
The requirements list can be any of the following
* 'F_CONTIGUOUS' ('F') - ensure a Fortran-contiguous array
* 'C_CONTIGUOUS' ('C') - ensure a C-contiguous array
* 'ALIGNED' ('A') - ensure a data-type aligned array
* 'WRITEABLE' ('W') - ensure a writable array
* 'OWNDATA' ('O') - ensure an array that owns its own data
* 'ENSUREARRAY', ('E') - ensure a base array, instead of a subclass
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
Array with specified requirements and type if given.
See Also
--------
asarray : Convert input to an ndarray.
asanyarray : Convert to an ndarray, but pass through ndarray subclasses.
ascontiguousarray : Convert input to a contiguous array.
asfortranarray : Convert input to an ndarray with column-major
memory order.
ndarray.flags : Information about the memory layout of the array.
Notes
-----
The returned array will be guaranteed to have the listed requirements
by making a copy if needed.
Examples
--------
>>> import numpy as np
>>> x = np.arange(6).reshape(2,3)
>>> x.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
>>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F'])
>>> y.flags
C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
numpy.reshape
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
reshape(a, /, shape=None, order='C', *, newshape=None, copy=None)
Gives a new shape to an array without changing its data.
Parameters
----------
a : array_like
Array to be reshaped.
shape : int or tuple of ints
The new shape should be compatible with the original shape. If
an integer, then the result will be a 1-D array of that length.
One shape dimension can be -1. In this case, the value is
inferred from the length of the array and remaining dimensions.
order : {'C', 'F', 'A'}, optional
Read the elements of ``a`` using this index order, and place the
elements into the reshaped array using this index order. 'C'
means to read / write the elements using C-like index order,
with the last axis index changing fastest, back to the first
axis index changing slowest. 'F' means to read / write the
elements using Fortran-like index order, with the first index
changing fastest, and the last index changing slowest. Note that
the 'C' and 'F' options take no account of the memory layout of
the underlying array, and only refer to the order of indexing.
'A' means to read / write the elements in Fortran-like index
order if ``a`` is Fortran *contiguous* in memory, C-like order
otherwise.
newshape : int or tuple of ints
.. deprecated:: 2.1
Replaced by ``shape`` argument. Retained for backward
compatibility.
copy : bool, optional
If ``True``, then the array data is copied. If ``None``, a copy will
only be made if it's required by ``order``. For ``False`` it raises
a ``ValueError`` if a copy cannot be avoided. Default: ``None``.
Returns
-------
reshaped_array : ndarray
This will be a new view object if possible; otherwise, it will
be a copy. Note there is no guarantee of the *memory layout* (C- or
Fortran- contiguous) of the returned array.
See Also
--------
ndarray.reshape : Equivalent method.
Notes
-----
It is not always possible to change the shape of an array without copying
the data.
The ``order`` keyword gives the index ordering both for *fetching*
the values from ``a``, and then *placing* the values into the output
array. For example, let's say you have an array:
>>> a = np.arange(6).reshape((3, 2))
>>> a
array([[0, 1],
[2, 3],
[4, 5]])
You can think of reshaping as first raveling the array (using the given
index order), then inserting the elements from the raveled array into the
new array using the same kind of index ordering as was used for the
raveling.
>>> np.reshape(a, (2, 3)) # C-like index ordering
array([[0, 1, 2],
[3, 4, 5]])
>>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
array([[0, 1, 2],
[3, 4, 5]])
>>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
array([[0, 4, 3],
[2, 1, 5]])
>>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
array([[0, 4, 3],
[2, 1, 5]])
Examples
--------
>>> import numpy as np
>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, 6)
array([1, 2, 3, 4, 5, 6])
>>> np.reshape(a, 6, order='F')
array([1, 4, 2, 5, 3, 6])
>>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
array([[1, 2],
[3, 4],
[5, 6]])
numpy.resize
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
resize(a, new_shape)
Return a new array with the specified shape.
If the new array is larger than the original array, then the new
array is filled with repeated copies of `a`. Note that this behavior
is different from a.resize(new_shape) which fills with zeros instead
of repeated copies of `a`.
Parameters
----------
a : array_like
Array to be resized.
new_shape : int or tuple of int
Shape of resized array.
Returns
-------
reshaped_array : ndarray
The new array is formed from the data in the old array, repeated
if necessary to fill out the required number of elements. The
data are repeated iterating over the array in C-order.
See Also
--------
numpy.reshape : Reshape an array without changing the total size.
numpy.pad : Enlarge and pad an array.
numpy.repeat : Repeat elements of an array.
ndarray.resize : resize an array in-place.
Notes
-----
When the total size of the array does not change `~numpy.reshape` should
be used. In most other cases either indexing (to reduce the size)
or padding (to increase the size) may be a more appropriate solution.
Warning: This functionality does **not** consider axes separately,
i.e. it does not apply interpolation/extrapolation.
It fills the return array with the required number of elements, iterating
over `a` in C-order, disregarding axes (and cycling back from the start if
the new shape is larger). This functionality is therefore not suitable to
resize images, or data where each axis represents a separate and distinct
entity.
Examples
--------
>>> import numpy as np
>>> a = np.array([[0,1],[2,3]])
>>> np.resize(a,(2,3))
array([[0, 1, 2],
[3, 0, 1]])
>>> np.resize(a,(1,4))
array([[0, 1, 2, 3]])
>>> np.resize(a,(2,4))
array([[0, 1, 2, 3],
[0, 1, 2, 3]])
numpy.result_type
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
result_type(...)
result_type(*arrays_and_dtypes)
Returns the type that results from applying the NumPy
type promotion rules to the arguments.
Type promotion in NumPy works similarly to the rules in languages
like C++, with some slight differences. When both scalars and
arrays are used, the array's type takes precedence and the actual value
of the scalar is taken into account.
For example, calculating 3*a, where a is an array of 32-bit floats,
intuitively should result in a 32-bit float output. If the 3 is a
32-bit integer, the NumPy rules indicate it can't convert losslessly
into a 32-bit float, so a 64-bit float should be the result type.
By examining the value of the constant, '3', we see that it fits in
an 8-bit integer, which can be cast losslessly into the 32-bit float.
Parameters
----------
arrays_and_dtypes : list of arrays and dtypes
The operands of some operation whose result type is needed.
Returns
-------
out : dtype
The result type.
See also
--------
dtype, promote_types, min_scalar_type, can_cast
Notes
-----
.. versionadded:: 1.6.0
The specific algorithm used is as follows.
Categories are determined by first checking which of boolean,
integer (int/uint), or floating point (float/complex) the maximum
kind of all the arrays and the scalars are.
If there are only scalars or the maximum category of the scalars
is higher than the maximum category of the arrays,
the data types are combined with :func:`promote_types`
to produce the return value.
Otherwise, `min_scalar_type` is called on each scalar, and
the resulting data types are all combined with :func:`promote_types`
to produce the return value.
The set of int values is not a subset of the uint values for types
with the same number of bits, something not reflected in
:func:`min_scalar_type`, but handled as a special case in `result_type`.
Examples
--------
>>> import numpy as np
>>> np.result_type(3, np.arange(7, dtype='i1'))
dtype('int8')
>>> np.result_type('i4', 'c8')
dtype('complex128')
>>> np.result_type(3.0, -2)
dtype('float64')
numpy.right_shift
Python Library Documentation: ufunc
right_shift = <ufunc 'right_shift'>
right_shift(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Shift the bits of an integer to the right.
Bits are shifted to the right `x2`. Because the internal
representation of numbers is in binary format, this operation is
equivalent to dividing `x1` by ``2**x2``.
Parameters
----------
x1 : array_like, int
Input values.
x2 : array_like, int
Number of bits to remove at the right of `x1`.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray, int
Return `x1` with bits shifted `x2` times to the right.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
left_shift : Shift the bits of an integer to the left.
binary_repr : Return the binary representation of the input number
as a string.
Examples
--------
>>> import numpy as np
>>> np.binary_repr(10)
'1010'
>>> np.right_shift(10, 1)
5
>>> np.binary_repr(5)
'101'
>>> np.right_shift(10, [1,2,3])
array([5, 2, 1])
The ``>>`` operator can be used as a shorthand for ``np.right_shift`` on
ndarrays.
>>> x1 = 10
>>> x2 = np.array([1,2,3])
>>> x1 >> x2
array([5, 2, 1])
numpy.rint
Python Library Documentation: ufunc
rint = <ufunc 'rint'>
rint(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Round elements of the array to the nearest integer.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Output array is same shape and type as `x`.
This is a scalar if `x` is a scalar.
See Also
--------
fix, ceil, floor, trunc
Notes
-----
For values exactly halfway between rounded decimal values, NumPy
rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
-0.5 and 0.5 round to 0.0, etc.
Examples
--------
>>> import numpy as np
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.rint(a)
array([-2., -2., -0., 0., 2., 2., 2.])
numpy.roll
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
roll(a, shift, axis=None)
Roll array elements along a given axis.
Elements that roll beyond the last position are re-introduced at
the first.
Parameters
----------
a : array_like
Input array.
shift : int or tuple of ints
The number of places by which elements are shifted. If a tuple,
then `axis` must be a tuple of the same size, and each of the
given axes is shifted by the corresponding number. If an int
while `axis` is a tuple of ints, then the same value is used for
all given axes.
axis : int or tuple of ints, optional
Axis or axes along which elements are shifted. By default, the
array is flattened before shifting, after which the original
shape is restored.
Returns
-------
res : ndarray
Output array, with the same shape as `a`.
See Also
--------
rollaxis : Roll the specified axis backwards, until it lies in a
given position.
Notes
-----
.. versionadded:: 1.12.0
Supports rolling over multiple dimensions simultaneously.
Examples
--------
>>> import numpy as np
>>> x = np.arange(10)
>>> np.roll(x, 2)
array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
>>> np.roll(x, -2)
array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
>>> x2 = np.reshape(x, (2, 5))
>>> x2
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> np.roll(x2, 1)
array([[9, 0, 1, 2, 3],
[4, 5, 6, 7, 8]])
>>> np.roll(x2, -1)
array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 0]])
>>> np.roll(x2, 1, axis=0)
array([[5, 6, 7, 8, 9],
[0, 1, 2, 3, 4]])
>>> np.roll(x2, -1, axis=0)
array([[5, 6, 7, 8, 9],
[0, 1, 2, 3, 4]])
>>> np.roll(x2, 1, axis=1)
array([[4, 0, 1, 2, 3],
[9, 5, 6, 7, 8]])
>>> np.roll(x2, -1, axis=1)
array([[1, 2, 3, 4, 0],
[6, 7, 8, 9, 5]])
>>> np.roll(x2, (1, 1), axis=(1, 0))
array([[9, 5, 6, 7, 8],
[4, 0, 1, 2, 3]])
>>> np.roll(x2, (2, 1), axis=(1, 0))
array([[8, 9, 5, 6, 7],
[3, 4, 0, 1, 2]])
numpy.rollaxis
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
rollaxis(a, axis, start=0)
Roll the specified axis backwards, until it lies in a given position.
This function continues to be supported for backward compatibility, but you
should prefer `moveaxis`. The `moveaxis` function was added in NumPy
1.11.
Parameters
----------
a : ndarray
Input array.
axis : int
The axis to be rolled. The positions of the other axes do not
change relative to one another.
start : int, optional
When ``start <= axis``, the axis is rolled back until it lies in
this position. When ``start > axis``, the axis is rolled until it
lies before this position. The default, 0, results in a "complete"
roll. The following table describes how negative values of ``start``
are interpreted:
.. table::
:align: left
+-------------------+----------------------+
| ``start`` | Normalized ``start`` |
+===================+======================+
| ``-(arr.ndim+1)`` | raise ``AxisError`` |
+-------------------+----------------------+
| ``-arr.ndim`` | 0 |
+-------------------+----------------------+
| |vdots| | |vdots| |
+-------------------+----------------------+
| ``-1`` | ``arr.ndim-1`` |
+-------------------+----------------------+
| ``0`` | ``0`` |
+-------------------+----------------------+
| |vdots| | |vdots| |
+-------------------+----------------------+
| ``arr.ndim`` | ``arr.ndim`` |
+-------------------+----------------------+
| ``arr.ndim + 1`` | raise ``AxisError`` |
+-------------------+----------------------+
.. |vdots| unicode:: U+22EE .. Vertical Ellipsis
Returns
-------
res : ndarray
For NumPy >= 1.10.0 a view of `a` is always returned. For earlier
NumPy versions a view of `a` is returned only if the order of the
axes is changed, otherwise the input array is returned.
See Also
--------
moveaxis : Move array axes to new positions.
roll : Roll the elements of an array by a number of positions along a
given axis.
Examples
--------
>>> import numpy as np
>>> a = np.ones((3,4,5,6))
>>> np.rollaxis(a, 3, 1).shape
(3, 6, 4, 5)
>>> np.rollaxis(a, 2).shape
(5, 3, 4, 6)
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)
numpy.roots
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
roots(p)
Return the roots of a polynomial with coefficients given in p.
.. note::
This forms part of the old polynomial API. Since version 1.4, the
new polynomial API defined in `numpy.polynomial` is preferred.
A summary of the differences can be found in the
:doc:`transition guide </reference/routines.polynomials>`.
The values in the rank-1 array `p` are coefficients of a polynomial.
If the length of `p` is n+1 then the polynomial is described by::
p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]
Parameters
----------
p : array_like
Rank-1 array of polynomial coefficients.
Returns
-------
out : ndarray
An array containing the roots of the polynomial.
Raises
------
ValueError
When `p` cannot be converted to a rank-1 array.
See also
--------
poly : Find the coefficients of a polynomial with a given sequence
of roots.
polyval : Compute polynomial values.
polyfit : Least squares polynomial fit.
poly1d : A one-dimensional polynomial class.
Notes
-----
The algorithm relies on computing the eigenvalues of the
companion matrix [1]_.
References
----------
.. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK:
Cambridge University Press, 1999, pp. 146-7.
Examples
--------
>>> import numpy as np
>>> coeff = [3.2, 2, 1]
>>> np.roots(coeff)
array([-0.3125+0.46351241j, -0.3125-0.46351241j])
numpy.rot90
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
rot90(m, k=1, axes=(0, 1))
Rotate an array by 90 degrees in the plane specified by axes.
Rotation direction is from the first towards the second axis.
This means for a 2D array with the default `k` and `axes`, the
rotation will be counterclockwise.
Parameters
----------
m : array_like
Array of two or more dimensions.
k : integer
Number of times the array is rotated by 90 degrees.
axes : (2,) array_like
The array is rotated in the plane defined by the axes.
Axes must be different.
.. versionadded:: 1.12.0
Returns
-------
y : ndarray
A rotated view of `m`.
See Also
--------
flip : Reverse the order of elements in an array along the given axis.
fliplr : Flip an array horizontally.
flipud : Flip an array vertically.
Notes
-----
``rot90(m, k=1, axes=(1,0))`` is the reverse of
``rot90(m, k=1, axes=(0,1))``
``rot90(m, k=1, axes=(1,0))`` is equivalent to
``rot90(m, k=-1, axes=(0,1))``
Examples
--------
>>> import numpy as np
>>> m = np.array([[1,2],[3,4]], int)
>>> m
array([[1, 2],
[3, 4]])
>>> np.rot90(m)
array([[2, 4],
[1, 3]])
>>> np.rot90(m, 2)
array([[4, 3],
[2, 1]])
>>> m = np.arange(8).reshape((2,2,2))
>>> np.rot90(m, 1, (1,2))
array([[[1, 3],
[0, 2]],
[[5, 7],
[4, 6]]])
numpy.round
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
round(a, decimals=0, out=None)
Evenly round to the given number of decimals.
Parameters
----------
a : array_like
Input data.
decimals : int, optional
Number of decimal places to round to (default: 0). If
decimals is negative, it specifies the number of positions to
the left of the decimal point.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output, but the type of the output
values will be cast if necessary. See :ref:`ufuncs-output-type`
for more details.
Returns
-------
rounded_array : ndarray
An array of the same type as `a`, containing the rounded values.
Unless `out` was specified, a new array is created. A reference to
the result is returned.
The real and imaginary parts of complex numbers are rounded
separately. The result of rounding a float is a float.
See Also
--------
ndarray.round : equivalent method
around : an alias for this function
ceil, fix, floor, rint, trunc
Notes
-----
For values exactly halfway between rounded decimal values, NumPy
rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
-0.5 and 0.5 round to 0.0, etc.
``np.round`` uses a fast but sometimes inexact algorithm to round
floating-point datatypes. For positive `decimals` it is equivalent to
``np.true_divide(np.rint(a * 10**decimals), 10**decimals)``, which has
error due to the inexact representation of decimal fractions in the IEEE
floating point standard [1]_ and errors introduced when scaling by powers
of ten. For instance, note the extra "1" in the following:
>>> np.round(56294995342131.5, 3)
56294995342131.51
If your goal is to print such values with a fixed number of decimals, it is
preferable to use numpy's float printing routines to limit the number of
printed decimals:
>>> np.format_float_positional(56294995342131.5, precision=3)
'56294995342131.5'
The float printing routines use an accurate but much more computationally
demanding algorithm to compute the number of digits after the decimal
point.
Alternatively, Python's builtin `round` function uses a more accurate
but slower algorithm for 64-bit floating point values:
>>> round(56294995342131.5, 3)
56294995342131.5
>>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997
(16.06, 16.05)
References
----------
.. [1] "Lecture Notes on the Status of IEEE 754", William Kahan,
https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
Examples
--------
>>> import numpy as np
>>> np.round([0.37, 1.64])
array([0., 2.])
>>> np.round([0.37, 1.64], decimals=1)
array([0.4, 1.6])
>>> np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([0., 2., 2., 4., 4.])
>>> np.round([1,2,3,11], decimals=1) # ndarray of ints is returned
array([ 1, 2, 3, 11])
>>> np.round([1,2,3,11], decimals=-1)
array([ 0, 0, 0, 10])
numpy.row_stack
Python Library Documentation: function row_stack in module numpy
row_stack(tup, *, dtype=None, casting='same_kind')
Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays
of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by
`vsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of ndarrays
The arrays must have the same shape along all but the first axis.
1-D arrays must have the same length.
dtype : str or dtype
If provided, the destination array will have this dtype. Cannot be
provided together with `out`.
.. versionadded:: 1.24
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'same_kind'.
.. versionadded:: 1.24
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 2-D.
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
block : Assemble an nd-array from nested lists of blocks.
hstack : Stack arrays in sequence horizontally (column wise).
dstack : Stack arrays in sequence depth wise (along third axis).
column_stack : Stack 1-D arrays as columns into a 2-D array.
vsplit : Split an array into multiple sub-arrays vertically (row-wise).
unstack : Split an array into a tuple of sub-arrays along an axis.
Examples
--------
>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.vstack((a,b))
array([[1, 2, 3],
[4, 5, 6]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[4], [5], [6]])
>>> np.vstack((a,b))
array([[1],
[2],
[3],
[4],
[5],
[6]])
numpy.s_
Python Library Documentation: IndexExpression in module numpy.lib._index_tricks_impl object class IndexExpression(builtins.object) | IndexExpression(maketuple) | | A nicer way to build up index tuples for arrays. | | .. note:: | Use one of the two predefined instances ``index_exp`` or `s_` | rather than directly using `IndexExpression`. | | For any index combination, including slicing and axis insertion, | ``a[indices]`` is the same as ``a[np.index_exp[indices]]`` for any | array `a`. However, ``np.index_exp[indices]`` can be used anywhere | in Python code and returns a tuple of slice objects that can be | used in the construction of complex index expressions. | | Parameters | ---------- | maketuple : bool | If True, always returns a tuple. | | See Also | -------- | s_ : Predefined instance without tuple conversion: | `s_ = IndexExpression(maketuple=False)`. | The ``index_exp`` is another predefined instance that | always returns a tuple: | `index_exp = IndexExpression(maketuple=True)`. | | Notes | ----- | You can do all this with :class:`slice` plus a few special objects, | but there's a lot to remember and this version is simpler because | it uses the standard array indexing syntax. | | Examples | -------- | >>> import numpy as np | >>> np.s_[2::2] | slice(2, None, 2) | >>> np.index_exp[2::2] | (slice(2, None, 2),) | | >>> np.array([0, 1, 2, 3, 4])[np.s_[2::2]] | array([2, 4]) | | Methods defined here: | | __getitem__(self, item) | | __init__(self, maketuple) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | maketuple
numpy.save
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
save(file, arr, allow_pickle=True, fix_imports=<no value>)
Save an array to a binary file in NumPy ``.npy`` format.
Parameters
----------
file : file, str, or pathlib.Path
File or filename to which the data is saved. If file is a file-object,
then the filename is unchanged. If file is a string or Path,
a ``.npy`` extension will be appended to the filename if it does not
already have one.
arr : array_like
Array data to be saved.
allow_pickle : bool, optional
Allow saving object arrays using Python pickles. Reasons for
disallowing pickles include security (loading pickled data can execute
arbitrary code) and portability (pickled objects may not be loadable
on different Python installations, for example if the stored objects
require libraries that are not available, and not all pickled data is
compatible between different versions of Python).
Default: True
fix_imports : bool, optional
The `fix_imports` flag is deprecated and has no effect.
.. deprecated:: 2.1
This flag is ignored since NumPy 1.17 and was only needed to
support loading some files in Python 2 written in Python 3.
See Also
--------
savez : Save several arrays into a ``.npz`` archive
savetxt, load
Notes
-----
For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.
Any data saved to the file is appended to the end of the file.
Examples
--------
>>> import numpy as np
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> np.save(outfile, x)
>>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file
>>> np.load(outfile)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> with open('test.npy', 'wb') as f:
... np.save(f, np.array([1, 2]))
... np.save(f, np.array([1, 3]))
>>> with open('test.npy', 'rb') as f:
... a = np.load(f)
... b = np.load(f)
>>> print(a, b)
# [1 2] [1 3]
numpy.savetxt
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)
Save an array to a text file.
Parameters
----------
fname : filename, file handle or pathlib.Path
If the filename ends in ``.gz``, the file is automatically saved in
compressed gzip format. `loadtxt` understands gzipped files
transparently.
X : 1D or 2D array_like
Data to be saved to a text file.
fmt : str or sequence of strs, optional
A single format (%10.5f), a sequence of formats, or a
multi-format string, e.g. 'Iteration %d -- %10.5f', in which
case `delimiter` is ignored. For complex `X`, the legal options
for `fmt` are:
* a single specifier, ``fmt='%.4e'``, resulting in numbers formatted
like ``' (%s+%sj)' % (fmt, fmt)``
* a full string specifying every real and imaginary part, e.g.
``' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'`` for 3 columns
* a list of specifiers, one per column - in this case, the real
and imaginary part must have separate specifiers,
e.g. ``['%.3e + %.3ej', '(%.15e%+.15ej)']`` for 2 columns
delimiter : str, optional
String or character separating columns.
newline : str, optional
String or character separating lines.
.. versionadded:: 1.5.0
header : str, optional
String that will be written at the beginning of the file.
.. versionadded:: 1.7.0
footer : str, optional
String that will be written at the end of the file.
.. versionadded:: 1.7.0
comments : str, optional
String that will be prepended to the ``header`` and ``footer`` strings,
to mark them as comments. Default: '# ', as expected by e.g.
``numpy.loadtxt``.
.. versionadded:: 1.7.0
encoding : {None, str}, optional
Encoding used to encode the outputfile. Does not apply to output
streams. If the encoding is something other than 'bytes' or 'latin1'
you will not be able to load the file in NumPy versions < 1.14. Default
is 'latin1'.
.. versionadded:: 1.14.0
See Also
--------
save : Save an array to a binary file in NumPy ``.npy`` format
savez : Save several arrays into an uncompressed ``.npz`` archive
savez_compressed : Save several arrays into a compressed ``.npz`` archive
Notes
-----
Further explanation of the `fmt` parameter
(``%[flag]width[.precision]specifier``):
flags:
``-`` : left justify
``+`` : Forces to precede result with + or -.
``0`` : Left pad the number with zeros instead of space (see width).
width:
Minimum number of characters to be printed. The value is not truncated
if it has more characters.
precision:
- For integer specifiers (eg. ``d,i,o,x``), the minimum number of
digits.
- For ``e, E`` and ``f`` specifiers, the number of digits to print
after the decimal point.
- For ``g`` and ``G``, the maximum number of significant digits.
- For ``s``, the maximum number of characters.
specifiers:
``c`` : character
``d`` or ``i`` : signed decimal integer
``e`` or ``E`` : scientific notation with ``e`` or ``E``.
``f`` : decimal floating point
``g,G`` : use the shorter of ``e,E`` or ``f``
``o`` : signed octal
``s`` : string of characters
``u`` : unsigned decimal integer
``x,X`` : unsigned hexadecimal integer
This explanation of ``fmt`` is not complete, for an exhaustive
specification see [1]_.
References
----------
.. [1] `Format Specification Mini-Language
<https://docs.python.org/library/string.html#format-specification-mini-language>`_,
Python Documentation.
Examples
--------
>>> import numpy as np
>>> x = y = z = np.arange(0.0,5.0,1.0)
>>> np.savetxt('test.out', x, delimiter=',') # X is an array
>>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays
>>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation
numpy.savez
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
savez(file, *args, **kwds)
Save several arrays into a single file in uncompressed ``.npz`` format.
Provide arrays as keyword arguments to store them under the
corresponding name in the output file: ``savez(fn, x=x, y=y)``.
If arrays are specified as positional arguments, i.e., ``savez(fn,
x, y)``, their names will be `arr_0`, `arr_1`, etc.
Parameters
----------
file : file, str, or pathlib.Path
Either the filename (string) or an open file (file-like object)
where the data will be saved. If file is a string or a Path, the
``.npz`` extension will be appended to the filename if it is not
already there.
args : Arguments, optional
Arrays to save to the file. Please use keyword arguments (see
`kwds` below) to assign names to arrays. Arrays specified as
args will be named "arr_0", "arr_1", and so on.
kwds : Keyword arguments, optional
Arrays to save to the file. Each array will be saved to the
output file with its corresponding keyword name.
Returns
-------
None
See Also
--------
save : Save a single array to a binary file in NumPy format.
savetxt : Save an array to a file as plain text.
savez_compressed : Save several arrays into a compressed ``.npz`` archive
Notes
-----
The ``.npz`` file format is a zipped archive of files named after the
variables they contain. The archive is not compressed and each file
in the archive contains one variable in ``.npy`` format. For a
description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.
When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile`
object is returned. This is a dictionary-like object which can be queried
for its list of arrays (with the ``.files`` attribute), and for the arrays
themselves.
Keys passed in `kwds` are used as filenames inside the ZIP archive.
Therefore, keys should be valid filenames; e.g., avoid keys that begin with
``/`` or contain ``.``.
When naming variables with keyword arguments, it is not possible to name a
variable ``file``, as this would cause the ``file`` argument to be defined
twice in the call to ``savez``.
Examples
--------
>>> import numpy as np
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> y = np.sin(x)
Using `savez` with \*args, the arrays are saved with default names.
>>> np.savez(outfile, x, y)
>>> _ = outfile.seek(0) # Only needed to simulate closing & reopening file
>>> npzfile = np.load(outfile)
>>> npzfile.files
['arr_0', 'arr_1']
>>> npzfile['arr_0']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Using `savez` with \**kwds, the arrays are saved with the keyword names.
>>> outfile = TemporaryFile()
>>> np.savez(outfile, x=x, y=y)
>>> _ = outfile.seek(0)
>>> npzfile = np.load(outfile)
>>> sorted(npzfile.files)
['x', 'y']
>>> npzfile['x']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
numpy.savez_compressed
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
savez_compressed(file, *args, **kwds)
Save several arrays into a single file in compressed ``.npz`` format.
Provide arrays as keyword arguments to store them under the
corresponding name in the output file: ``savez_compressed(fn, x=x, y=y)``.
If arrays are specified as positional arguments, i.e.,
``savez_compressed(fn, x, y)``, their names will be `arr_0`, `arr_1`, etc.
Parameters
----------
file : file, str, or pathlib.Path
Either the filename (string) or an open file (file-like object)
where the data will be saved. If file is a string or a Path, the
``.npz`` extension will be appended to the filename if it is not
already there.
args : Arguments, optional
Arrays to save to the file. Please use keyword arguments (see
`kwds` below) to assign names to arrays. Arrays specified as
args will be named "arr_0", "arr_1", and so on.
kwds : Keyword arguments, optional
Arrays to save to the file. Each array will be saved to the
output file with its corresponding keyword name.
Returns
-------
None
See Also
--------
numpy.save : Save a single array to a binary file in NumPy format.
numpy.savetxt : Save an array to a file as plain text.
numpy.savez : Save several arrays into an uncompressed ``.npz`` file format
numpy.load : Load the files created by savez_compressed.
Notes
-----
The ``.npz`` file format is a zipped archive of files named after the
variables they contain. The archive is compressed with
``zipfile.ZIP_DEFLATED`` and each file in the archive contains one variable
in ``.npy`` format. For a description of the ``.npy`` format, see
:py:mod:`numpy.lib.format`.
When opening the saved ``.npz`` file with `load` a `~lib.npyio.NpzFile`
object is returned. This is a dictionary-like object which can be queried
for its list of arrays (with the ``.files`` attribute), and for the arrays
themselves.
Examples
--------
>>> import numpy as np
>>> test_array = np.random.rand(3, 2)
>>> test_vector = np.random.rand(4)
>>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector)
>>> loaded = np.load('/tmp/123.npz')
>>> print(np.array_equal(test_array, loaded['a']))
True
>>> print(np.array_equal(test_vector, loaded['b']))
True
numpy.sctypeDict
Python Library Documentation: dict object
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Built-in subclasses:
| StgDict
|
| Methods defined here:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
numpy.searchsorted
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
searchsorted(a, v, side='left', sorter=None)
Find indices where elements should be inserted to maintain order.
Find the indices into a sorted array `a` such that, if the
corresponding elements in `v` were inserted before the indices, the
order of `a` would be preserved.
Assuming that `a` is sorted:
====== ============================
`side` returned index `i` satisfies
====== ============================
left ``a[i-1] < v <= a[i]``
right ``a[i-1] <= v < a[i]``
====== ============================
Parameters
----------
a : 1-D array_like
Input array. If `sorter` is None, then it must be sorted in
ascending order, otherwise `sorter` must be an array of indices
that sort it.
v : array_like
Values to insert into `a`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given.
If 'right', return the last such index. If there is no suitable
index, return either 0 or N (where N is the length of `a`).
sorter : 1-D array_like, optional
Optional array of integer indices that sort array a into ascending
order. They are typically the result of argsort.
.. versionadded:: 1.7.0
Returns
-------
indices : int or array of ints
Array of insertion points with the same shape as `v`,
or an integer if `v` is a scalar.
See Also
--------
sort : Return a sorted copy of an array.
histogram : Produce histogram from 1-D data.
Notes
-----
Binary search is used to find the required insertion points.
As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing
`nan` values. The enhanced sort order is documented in `sort`.
This function uses the same algorithm as the builtin python
`bisect.bisect_left` (``side='left'``) and `bisect.bisect_right`
(``side='right'``) functions, which is also vectorized
in the `v` argument.
Examples
--------
>>> import numpy as np
>>> np.searchsorted([11,12,13,14,15], 13)
2
>>> np.searchsorted([11,12,13,14,15], 13, side='right')
3
>>> np.searchsorted([11,12,13,14,15], [-10, 20, 12, 13])
array([0, 5, 1, 2])
numpy.select
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
select(condlist, choicelist, default=0)
Return an array drawn from elements in choicelist, depending on conditions.
Parameters
----------
condlist : list of bool ndarrays
The list of conditions which determine from which array in `choicelist`
the output elements are taken. When multiple conditions are satisfied,
the first one encountered in `condlist` is used.
choicelist : list of ndarrays
The list of arrays from which the output elements are taken. It has
to be of the same length as `condlist`.
default : scalar, optional
The element inserted in `output` when all conditions evaluate to False.
Returns
-------
output : ndarray
The output at position m is the m-th element of the array in
`choicelist` where the m-th element of the corresponding array in
`condlist` is True.
See Also
--------
where : Return elements from one of two arrays depending on condition.
take, choose, compress, diag, diagonal
Examples
--------
>>> import numpy as np
Beginning with an array of integers from 0 to 5 (inclusive),
elements less than ``3`` are negated, elements greater than ``3``
are squared, and elements not meeting either of these conditions
(exactly ``3``) are replaced with a `default` value of ``42``.
>>> x = np.arange(6)
>>> condlist = [x<3, x>3]
>>> choicelist = [x, x**2]
>>> np.select(condlist, choicelist, 42)
array([ 0, 1, 2, 42, 16, 25])
When multiple conditions are satisfied, the first one encountered in
`condlist` is used.
>>> condlist = [x<=4, x>3]
>>> choicelist = [x, x**2]
>>> np.select(condlist, choicelist, 55)
array([ 0, 1, 2, 3, 4, 25])
numpy.set_printoptions
Python Library Documentation: function set_printoptions in module numpy
set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, *, legacy=None, override_repr=None)
Set printing options.
These options determine the way floating point numbers, arrays and
other NumPy objects are displayed.
Parameters
----------
precision : int or None, optional
Number of digits of precision for floating point output (default 8).
May be None if `floatmode` is not `fixed`, to print as many digits as
necessary to uniquely specify the value.
threshold : int, optional
Total number of array elements which trigger summarization
rather than full repr (default 1000).
To always use the full repr without summarization, pass `sys.maxsize`.
edgeitems : int, optional
Number of array items in summary at beginning and end of
each dimension (default 3).
linewidth : int, optional
The number of characters per line for the purpose of inserting
line breaks (default 75).
suppress : bool, optional
If True, always print floating point numbers using fixed point
notation, in which case numbers equal to zero in the current precision
will print as zero. If False, then scientific notation is used when
absolute value of the smallest number is < 1e-4 or the ratio of the
maximum absolute value to the minimum is > 1e3. The default is False.
nanstr : str, optional
String representation of floating point not-a-number (default nan).
infstr : str, optional
String representation of floating point infinity (default inf).
sign : string, either '-', '+', or ' ', optional
Controls printing of the sign of floating-point types. If '+', always
print the sign of positive values. If ' ', always prints a space
(whitespace character) in the sign position of positive values. If
'-', omit the sign character of positive values. (default '-')
.. versionchanged:: 2.0
The sign parameter can now be an integer type, previously
types were floating-point types.
formatter : dict of callables, optional
If not None, the keys should indicate the type(s) that the respective
formatting function applies to. Callables should return a string.
Types that are not specified (by their corresponding keys) are handled
by the default formatters. Individual types for which a formatter
can be set are:
- 'bool'
- 'int'
- 'timedelta' : a `numpy.timedelta64`
- 'datetime' : a `numpy.datetime64`
- 'float'
- 'longfloat' : 128-bit floats
- 'complexfloat'
- 'longcomplexfloat' : composed of two 128-bit floats
- 'numpystr' : types `numpy.bytes_` and `numpy.str_`
- 'object' : `np.object_` arrays
Other keys that can be used to set a group of types at once are:
- 'all' : sets all types
- 'int_kind' : sets 'int'
- 'float_kind' : sets 'float' and 'longfloat'
- 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
- 'str_kind' : sets 'numpystr'
floatmode : str, optional
Controls the interpretation of the `precision` option for
floating-point types. Can take the following values
(default maxprec_equal):
* 'fixed': Always print exactly `precision` fractional digits,
even if this would print more or fewer digits than
necessary to specify the value uniquely.
* 'unique': Print the minimum number of fractional digits necessary
to represent each value uniquely. Different elements may
have a different number of digits. The value of the
`precision` option is ignored.
* 'maxprec': Print at most `precision` fractional digits, but if
an element can be uniquely represented with fewer digits
only print it with that many.
* 'maxprec_equal': Print at most `precision` fractional digits,
but if every element in the array can be uniquely
represented with an equal number of fewer digits, use that
many digits for all elements.
legacy : string or `False`, optional
If set to the string ``'1.13'`` enables 1.13 legacy printing mode. This
approximates numpy 1.13 print output by including a space in the sign
position of floats and different behavior for 0d arrays. This also
enables 1.21 legacy printing mode (described below).
If set to the string ``'1.21'`` enables 1.21 legacy printing mode. This
approximates numpy 1.21 print output of complex structured dtypes
by not inserting spaces after commas that separate fields and after
colons.
If set to ``'1.25'`` approximates printing of 1.25 which mainly means
that numeric scalars are printed without their type information, e.g.
as ``3.0`` rather than ``np.float64(3.0)``.
If set to `False`, disables legacy mode.
Unrecognized strings will be ignored with a warning for forward
compatibility.
.. versionadded:: 1.14.0
.. versionchanged:: 1.22.0
.. versionchanged:: 2.0
override_repr: callable, optional
If set a passed function will be used for generating arrays' repr.
Other options will be ignored.
See Also
--------
get_printoptions, printoptions, array2string
Notes
-----
`formatter` is always reset with a call to `set_printoptions`.
Use `printoptions` as a context manager to set the values temporarily.
Examples
--------
Floating point precision can be set:
>>> import numpy as np
>>> np.set_printoptions(precision=4)
>>> np.array([1.123456789])
[1.1235]
Long arrays can be summarised:
>>> np.set_printoptions(threshold=5)
>>> np.arange(10)
array([0, 1, 2, ..., 7, 8, 9])
Small results can be suppressed:
>>> eps = np.finfo(float).eps
>>> x = np.arange(4.)
>>> x**2 - (x + eps)**2
array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00])
>>> np.set_printoptions(suppress=True)
>>> x**2 - (x + eps)**2
array([-0., -0., 0., 0.])
A custom formatter can be used to display array elements as desired:
>>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
>>> x = np.arange(3)
>>> x
array([int: 0, int: -1, int: -2])
>>> np.set_printoptions() # formatter gets reset
>>> x
array([0, 1, 2])
To put back the default options, you can use:
>>> np.set_printoptions(edgeitems=3, infstr='inf',
... linewidth=75, nanstr='nan', precision=8,
... suppress=False, threshold=1000, formatter=None)
Also to temporarily override options, use `printoptions`
as a context manager:
>>> with np.printoptions(precision=2, suppress=True, threshold=5):
... np.linspace(0, 10, 10)
array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ])
numpy.setbufsize
Python Library Documentation: function setbufsize in module numpy
setbufsize(size)
Set the size of the buffer used in ufuncs.
.. versionchanged:: 2.0
The scope of setting the buffer is tied to the `numpy.errstate`
context. Exiting a ``with errstate():`` will also restore the bufsize.
Parameters
----------
size : int
Size of buffer.
Returns
-------
bufsize : int
Previous size of ufunc buffer in bytes.
Examples
--------
When exiting a `numpy.errstate` context manager the bufsize is restored:
>>> import numpy as np
>>> with np.errstate():
... np.setbufsize(4096)
... print(np.getbufsize())
...
8192
4096
>>> np.getbufsize()
8192
numpy.setdiff1d
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
setdiff1d(ar1, ar2, assume_unique=False)
Find the set difference of two arrays.
Return the unique values in `ar1` that are not in `ar2`.
Parameters
----------
ar1 : array_like
Input array.
ar2 : array_like
Input comparison array.
assume_unique : bool
If True, the input arrays are both assumed to be unique, which
can speed up the calculation. Default is False.
Returns
-------
setdiff1d : ndarray
1D array of values in `ar1` that are not in `ar2`. The result
is sorted when `assume_unique=False`, but otherwise only sorted
if the input is sorted.
Examples
--------
>>> import numpy as np
>>> a = np.array([1, 2, 3, 2, 4, 1])
>>> b = np.array([3, 4, 5, 6])
>>> np.setdiff1d(a, b)
array([1, 2])
numpy.seterr
Python Library Documentation: function seterr in module numpy
seterr(all=None, divide=None, over=None, under=None, invalid=None)
Set how floating-point errors are handled.
Note that operations on integer scalar types (such as `int16`) are
handled like floating point, and are affected by these settings.
Parameters
----------
all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
Set treatment for all types of floating-point errors at once:
- ignore: Take no action when the exception occurs.
- warn: Print a :exc:`RuntimeWarning` (via the Python `warnings`
module).
- raise: Raise a :exc:`FloatingPointError`.
- call: Call a function specified using the `seterrcall` function.
- print: Print a warning directly to ``stdout``.
- log: Record error in a Log object specified by `seterrcall`.
The default is not to change the current behavior.
divide : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
Treatment for division by zero.
over : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
Treatment for floating-point overflow.
under : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
Treatment for floating-point underflow.
invalid : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional
Treatment for invalid floating-point operation.
Returns
-------
old_settings : dict
Dictionary containing the old settings.
See also
--------
seterrcall : Set a callback function for the 'call' mode.
geterr, geterrcall, errstate
Notes
-----
The floating-point exceptions are defined in the IEEE 754 standard [1]_:
- Division by zero: infinite result obtained from finite numbers.
- Overflow: result too large to be expressed.
- Underflow: result so close to zero that some precision
was lost.
- Invalid operation: result is not an expressible number, typically
indicates that a NaN was produced.
.. [1] https://en.wikipedia.org/wiki/IEEE_754
Examples
--------
>>> import numpy as np
>>> orig_settings = np.seterr(all='ignore') # seterr to known value
>>> np.int16(32000) * np.int16(3)
30464
>>> np.seterr(over='raise')
{'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
>>> old_settings = np.seterr(all='warn', over='raise')
>>> np.int16(32000) * np.int16(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FloatingPointError: overflow encountered in scalar multiply
>>> old_settings = np.seterr(all='print')
>>> np.geterr()
{'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
>>> np.int16(32000) * np.int16(3)
30464
>>> np.seterr(**orig_settings) # restore original
{'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
numpy.seterrcall
Python Library Documentation: function seterrcall in module numpy
seterrcall(func)
Set the floating-point error callback function or log object.
There are two ways to capture floating-point error messages. The first
is to set the error-handler to 'call', using `seterr`. Then, set
the function to call using this function.
The second is to set the error-handler to 'log', using `seterr`.
Floating-point errors then trigger a call to the 'write' method of
the provided object.
Parameters
----------
func : callable f(err, flag) or object with write method
Function to call upon floating-point errors ('call'-mode) or
object whose 'write' method is used to log such message ('log'-mode).
The call function takes two arguments. The first is a string describing
the type of error (such as "divide by zero", "overflow", "underflow",
or "invalid value"), and the second is the status flag. The flag is a
byte, whose four least-significant bits indicate the type of error, one
of "divide", "over", "under", "invalid"::
[0 0 0 0 divide over under invalid]
In other words, ``flags = divide + 2*over + 4*under + 8*invalid``.
If an object is provided, its write method should take one argument,
a string.
Returns
-------
h : callable, log instance or None
The old error handler.
See Also
--------
seterr, geterr, geterrcall
Examples
--------
Callback upon error:
>>> def err_handler(type, flag):
... print("Floating point error (%s), with flag %s" % (type, flag))
...
>>> import numpy as np
>>> orig_handler = np.seterrcall(err_handler)
>>> orig_err = np.seterr(all='call')
>>> np.array([1, 2, 3]) / 0.0
Floating point error (divide by zero), with flag 1
array([inf, inf, inf])
>>> np.seterrcall(orig_handler)
<function err_handler at 0x...>
>>> np.seterr(**orig_err)
{'divide': 'call', 'over': 'call', 'under': 'call', 'invalid': 'call'}
Log error message:
>>> class Log:
... def write(self, msg):
... print("LOG: %s" % msg)
...
>>> log = Log()
>>> saved_handler = np.seterrcall(log)
>>> save_err = np.seterr(all='log')
>>> np.array([1, 2, 3]) / 0.0
LOG: Warning: divide by zero encountered in divide
array([inf, inf, inf])
>>> np.seterrcall(orig_handler)
<numpy.Log object at 0x...>
>>> np.seterr(**orig_err)
{'divide': 'log', 'over': 'log', 'under': 'log', 'invalid': 'log'}
numpy.setxor1d
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
setxor1d(ar1, ar2, assume_unique=False)
Find the set exclusive-or of two arrays.
Return the sorted, unique values that are in only one (not both) of the
input arrays.
Parameters
----------
ar1, ar2 : array_like
Input arrays.
assume_unique : bool
If True, the input arrays are both assumed to be unique, which
can speed up the calculation. Default is False.
Returns
-------
setxor1d : ndarray
Sorted 1D array of unique values that are in only one of the input
arrays.
Examples
--------
>>> import numpy as np
>>> a = np.array([1, 2, 3, 2, 4])
>>> b = np.array([2, 3, 5, 7, 5])
>>> np.setxor1d(a,b)
array([1, 4, 5, 7])
numpy.shape
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
shape(a)
Return the shape of an array.
Parameters
----------
a : array_like
Input array.
Returns
-------
shape : tuple of ints
The elements of the shape tuple give the lengths of the
corresponding array dimensions.
See Also
--------
len : ``len(a)`` is equivalent to ``np.shape(a)[0]`` for N-D arrays with
``N>=1``.
ndarray.shape : Equivalent array method.
Examples
--------
>>> import numpy as np
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 3]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
>>> a = np.array([(1, 2), (3, 4), (5, 6)],
... dtype=[('x', 'i4'), ('y', 'i4')])
>>> np.shape(a)
(3,)
>>> a.shape
(3,)
numpy.short
Python Library Documentation: class int16 in module numpy class int16(signedinteger) | Signed integer type, compatible with C ``short``. | | :Character code: ``'h'`` | :Canonical name: `numpy.short` | :Alias on this platform (win32 AMD64): `numpy.int16`: 16-bit signed integer (``-32_768`` to ``32_767``). | | Method resolution order: | int16 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | int16.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.int16(127).bit_count() | 7 | >>> np.int16(-127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.show_config
Python Library Documentation: function show in module numpy.__config__
show(mode='stdout')
Show libraries and system information on which NumPy was built
and is being used
Parameters
----------
mode : {`'stdout'`, `'dicts'`}, optional.
Indicates how to display the config information.
`'stdout'` prints to console, `'dicts'` returns a dictionary
of the configuration.
Returns
-------
out : {`dict`, `None`}
If mode is `'dicts'`, a dict is returned, else None
See Also
--------
get_include : Returns the directory containing NumPy C
header files.
Notes
-----
1. The `'stdout'` mode will give more readable
output if ``pyyaml`` is installed
numpy.show_runtime
Python Library Documentation: function show_runtime in module numpy
show_runtime()
Print information about various resources in the system
including available intrinsic support and BLAS/LAPACK library
in use
.. versionadded:: 1.24.0
See Also
--------
show_config : Show libraries in the system on which NumPy was built.
Notes
-----
1. Information is derived with the help of `threadpoolctl <https://pypi.org/project/threadpoolctl/>`_
library if available.
2. SIMD related information is derived from ``__cpu_features__``,
``__cpu_baseline__`` and ``__cpu_dispatch__``
numpy.sign
Python Library Documentation: ufunc
sign = <ufunc 'sign'>
sign(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns an element-wise indication of the sign of a number.
The `sign` function returns ``-1 if x < 0, 0 if x==0, 1 if x > 0``. nan
is returned for nan inputs.
For complex inputs, the `sign` function returns ``x / abs(x)``, the
generalization of the above (and ``0 if x==0``).
.. versionchanged:: 2.0.0
Definition of complex sign changed to follow the Array API standard.
Parameters
----------
x : array_like
Input values.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The sign of `x`.
This is a scalar if `x` is a scalar.
Notes
-----
There is more than one definition of sign in common use for complex
numbers. The definition used here, :math:`x/|x|`, is the more common
and useful one, but is different from the one used in numpy prior to
version 2.0, :math:`x/\sqrt{x*x}`, which is equivalent to
``sign(x.real) + 0j if x.real != 0 else sign(x.imag) + 0j``.
Examples
--------
>>> import numpy as np
>>> np.sign([-5., 4.5])
array([-1., 1.])
>>> np.sign(0)
0
>>> np.sign([3-4j, 8j])
array([0.6-0.8j, 0. +1.j ])
numpy.signbit
Python Library Documentation: ufunc
signbit = <ufunc 'signbit'>
signbit(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns element-wise True where signbit is set (less than zero).
Parameters
----------
x : array_like
The input value(s).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
result : ndarray of bool
Output array, or reference to `out` if that was supplied.
This is a scalar if `x` is a scalar.
Examples
--------
>>> import numpy as np
>>> np.signbit(-1.2)
True
>>> np.signbit(np.array([1, -2.3, 2.1]))
array([False, True, False])
numpy.signedinteger
Python Library Documentation: class signedinteger in module numpy class signedinteger(integer) | Abstract base class of all signed integer scalar types. | | Method resolution order: | signedinteger | integer | number | generic | builtins.object | | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Class methods inherited from number: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Data and other attributes inherited from generic: | | __hash__ = None
numpy.sin
Python Library Documentation: ufunc
sin = <ufunc 'sin'>
sin(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Trigonometric sine, element-wise.
Parameters
----------
x : array_like
Angle, in radians (:math:`2 \pi` rad equals 360 degrees).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : array_like
The sine of each element of x.
This is a scalar if `x` is a scalar.
See Also
--------
arcsin, sinh, cos
Notes
-----
The sine is one of the fundamental functions of trigonometry (the
mathematical study of triangles). Consider a circle of radius 1
centered on the origin. A ray comes in from the :math:`+x` axis, makes
an angle at the origin (measured counter-clockwise from that axis), and
departs from the origin. The :math:`y` coordinate of the outgoing
ray's intersection with the unit circle is the sine of that angle. It
ranges from -1 for :math:`x=3\pi / 2` to +1 for :math:`\pi / 2.` The
function has zeroes where the angle is a multiple of :math:`\pi`.
Sines of angles between :math:`\pi` and :math:`2\pi` are negative.
The numerous properties of the sine and related functions are included
in any standard trigonometry text.
Examples
--------
>>> import numpy as np
Print sine of one angle:
>>> np.sin(np.pi/2.)
1.0
Print sines of an array of angles given in degrees:
>>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. )
array([ 0. , 0.5 , 0.70710678, 0.8660254 , 1. ])
Plot the sine function:
>>> import matplotlib.pylab as plt
>>> x = np.linspace(-np.pi, np.pi, 201)
>>> plt.plot(x, np.sin(x))
>>> plt.xlabel('Angle [rad]')
>>> plt.ylabel('sin(x)')
>>> plt.axis('tight')
>>> plt.show()
numpy.sinc
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
sinc(x)
Return the normalized sinc function.
The sinc function is equal to :math:`\sin(\pi x)/(\pi x)` for any argument
:math:`x\ne 0`. ``sinc(0)`` takes the limit value 1, making ``sinc`` not
only everywhere continuous but also infinitely differentiable.
.. note::
Note the normalization factor of ``pi`` used in the definition.
This is the most commonly used definition in signal processing.
Use ``sinc(x / np.pi)`` to obtain the unnormalized sinc function
:math:`\sin(x)/x` that is more common in mathematics.
Parameters
----------
x : ndarray
Array (possibly multi-dimensional) of values for which to calculate
``sinc(x)``.
Returns
-------
out : ndarray
``sinc(x)``, which has the same shape as the input.
Notes
-----
The name sinc is short for "sine cardinal" or "sinus cardinalis".
The sinc function is used in various signal processing applications,
including in anti-aliasing, in the construction of a Lanczos resampling
filter, and in interpolation.
For bandlimited interpolation of discrete-time signals, the ideal
interpolation kernel is proportional to the sinc function.
References
----------
.. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
Resource. https://mathworld.wolfram.com/SincFunction.html
.. [2] Wikipedia, "Sinc function",
https://en.wikipedia.org/wiki/Sinc_function
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-4, 4, 41)
>>> np.sinc(x)
array([-3.89804309e-17, -4.92362781e-02, -8.40918587e-02, # may vary
-8.90384387e-02, -5.84680802e-02, 3.89804309e-17,
6.68206631e-02, 1.16434881e-01, 1.26137788e-01,
8.50444803e-02, -3.89804309e-17, -1.03943254e-01,
-1.89206682e-01, -2.16236208e-01, -1.55914881e-01,
3.89804309e-17, 2.33872321e-01, 5.04551152e-01,
7.56826729e-01, 9.35489284e-01, 1.00000000e+00,
9.35489284e-01, 7.56826729e-01, 5.04551152e-01,
2.33872321e-01, 3.89804309e-17, -1.55914881e-01,
-2.16236208e-01, -1.89206682e-01, -1.03943254e-01,
-3.89804309e-17, 8.50444803e-02, 1.26137788e-01,
1.16434881e-01, 6.68206631e-02, 3.89804309e-17,
-5.84680802e-02, -8.90384387e-02, -8.40918587e-02,
-4.92362781e-02, -3.89804309e-17])
>>> plt.plot(x, np.sinc(x))
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Sinc Function")
Text(0.5, 1.0, 'Sinc Function')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("X")
Text(0.5, 0, 'X')
>>> plt.show()
numpy.single
Python Library Documentation: class float32 in module numpy class float32(floating) | Single-precision floating-point number type, compatible with C ``float``. | | :Character code: ``'f'`` | :Canonical name: `numpy.single` | :Alias on this platform (win32 AMD64): `numpy.float32`: 32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa. | | Method resolution order: | float32 | floating | inexact | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __int__(self, /) | int(self) | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | as_integer_ratio(...) | single.as_integer_ratio() -> (int, int) | | Return a pair of integers, whose ratio is exactly equal to the original | floating point number, and with a positive denominator. | Raise `OverflowError` on infinities and a `ValueError` on NaNs. | | >>> np.single(10.0).as_integer_ratio() | (10, 1) | >>> np.single(0.0).as_integer_ratio() | (0, 1) | >>> np.single(-.25).as_integer_ratio() | (-1, 4) | | is_integer(...) | single.is_integer() -> bool | | Return ``True`` if the floating point number is finite with integral | value, and ``False`` otherwise. | | .. versionadded:: 1.22 | | Examples | -------- | >>> np.single(-2.0).is_integer() | True | >>> np.single(3.2).is_integer() | False | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from floating: | | __round__(...) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __or__(self, value, /) | Return self|value. | | __rand__(self, value, /) | Return value&self. | | __reduce__(...) | Helper for pickle. | | __rlshift__(self, value, /) | Return value<<self. | | __ror__(self, value, /) | Return value|self. | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.sinh
Python Library Documentation: ufunc
sinh = <ufunc 'sinh'>
sinh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Hyperbolic sine, element-wise.
Equivalent to ``1/2 * (np.exp(x) - np.exp(-x))`` or
``-1j * np.sin(1j*x)``.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding hyperbolic sine values.
This is a scalar if `x` is a scalar.
Notes
-----
If `out` is provided, the function writes the result into it,
and returns a reference to `out`. (See Examples)
References
----------
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.
New York, NY: Dover, 1972, pg. 83.
Examples
--------
>>> import numpy as np
>>> np.sinh(0)
0.0
>>> np.sinh(np.pi*1j/2)
1j
>>> np.sinh(np.pi*1j) # (exact value is 0)
1.2246063538223773e-016j
>>> # Discrepancy due to vagaries of floating point arithmetic.
>>> # Example of providing the optional output parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.sinh([0.1], out1)
>>> out2 is out1
True
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.sinh(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
numpy.size
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
size(a, axis=None)
Return the number of elements along a given axis.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which the elements are counted. By default, give
the total number of elements.
Returns
-------
element_count : int
Number of elements along the specified axis.
See Also
--------
shape : dimensions of array
ndarray.shape : dimensions of array
ndarray.size : number of elements in array
Examples
--------
>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
numpy.sort
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
sort(a, axis=-1, kind=None, order=None, *, stable=None)
Return a sorted copy of an array.
Parameters
----------
a : array_like
Array to be sorted.
axis : int 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 : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
Sorting algorithm. The default is 'quicksort'. Note that both 'stable'
and 'mergesort' use timsort or radix sort under the covers and,
in general, the actual implementation will vary with data type.
The 'mergesort' option is retained for backwards compatibility.
.. versionchanged:: 1.15.0.
The 'stable' option was added.
order : str 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, and 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.
stable : bool, optional
Sort stability. If ``True``, the returned array will maintain
the relative order of ``a`` values which compare as equal.
If ``False`` or ``None``, this is not guaranteed. Internally,
this option selects ``kind='stable'``. Default: ``None``.
.. versionadded:: 2.0.0
Returns
-------
sorted_array : ndarray
Array of the same type and shape as `a`.
See Also
--------
ndarray.sort : Method to sort an array in-place.
argsort : Indirect sort.
lexsort : Indirect stable sort on multiple keys.
searchsorted : Find elements in a sorted array.
partition : Partial sort.
Notes
-----
The various sorting 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 four algorithms implemented in NumPy have the following
properties:
=========== ======= ============= ============ ========
kind speed worst case work space stable
=========== ======= ============= ============ ========
'quicksort' 1 O(n^2) 0 no
'heapsort' 3 O(n*log(n)) 0 no
'mergesort' 2 O(n*log(n)) ~n/2 yes
'timsort' 2 O(n*log(n)) ~n/2 yes
=========== ======= ============= ============ ========
.. note:: The datatype determines which of 'mergesort' or 'timsort'
is actually used, even if 'mergesort' is specified. User selection
at a finer scale is not currently available.
For performance, ``sort`` makes a temporary copy if needed to make the data
`contiguous <https://numpy.org/doc/stable/glossary.html#term-contiguous>`_
in memory along the sort axis. For even better performance and reduced
memory consumption, ensure that the array is already contiguous along the
sort 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.
Previous to numpy 1.4.0 sorting real and complex arrays containing nan
values led to undefined behaviour. In numpy versions >= 1.4.0 nan
values are sorted to the end. The extended sort order is:
* Real: [R, nan]
* Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
where R is a non-nan real value. Complex values with the same nan
placements are sorted according to the non-nan part if it exists.
Non-nan values are sorted as before.
.. versionadded:: 1.12.0
quicksort has been changed to:
`introsort <https://en.wikipedia.org/wiki/Introsort>`_.
When sorting does not make enough progress it switches to
`heapsort <https://en.wikipedia.org/wiki/Heapsort>`_.
This implementation makes quicksort O(n*log(n)) in the worst case.
'stable' automatically chooses the best stable sorting algorithm
for the data type being sorted.
It, along with 'mergesort' is currently mapped to
`timsort <https://en.wikipedia.org/wiki/Timsort>`_
or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_
depending on the data type.
API forward compatibility currently limits the
ability to select the implementation and it is hardwired for the different
data types.
.. versionadded:: 1.17.0
Timsort is added for better performance on already or nearly
sorted data. On random data timsort is almost identical to
mergesort. It is now used for stable sort while quicksort is still the
default sort if none is chosen. For timsort details, refer to
`CPython listsort.txt
<https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_
'mergesort' and 'stable' are mapped to radix sort for integer data types.
Radix sort is an O(n) sort instead of O(n log n).
.. versionchanged:: 1.18.0
NaT now sorts to the end of arrays for consistency with NaN.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1,4],[3,1]])
>>> np.sort(a) # sort along the last axis
array([[1, 4],
[1, 3]])
>>> np.sort(a, axis=None) # sort the flattened array
array([1, 1, 3, 4])
>>> np.sort(a, axis=0) # sort along the first axis
array([[1, 1],
[3, 4]])
Use the `order` keyword to specify a field to use when sorting a
structured array:
>>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
>>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
... ('Galahad', 1.7, 38)]
>>> a = np.array(values, dtype=dtype) # create a structured array
>>> np.sort(a, order='height') # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
('Lancelot', 1.8999999999999999, 38)],
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
Sort by age, then height if ages are equal:
>>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
('Arthur', 1.8, 41)],
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
numpy.sort_complex
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
sort_complex(a)
Sort a complex array using the real part first, then the imaginary part.
Parameters
----------
a : array_like
Input array
Returns
-------
out : complex ndarray
Always returns a sorted complex array.
Examples
--------
>>> import numpy as np
>>> np.sort_complex([5, 3, 6, 2, 1])
array([1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j])
>>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j])
array([1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j])
numpy.spacing
Python Library Documentation: ufunc
spacing = <ufunc 'spacing'>
spacing(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the distance between x and the nearest adjacent number.
Parameters
----------
x : array_like
Values to find the spacing of.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
The spacing of values of `x`.
This is a scalar if `x` is a scalar.
Notes
-----
It can be considered as a generalization of EPS:
``spacing(np.float64(1)) == np.finfo(np.float64).eps``, and there
should not be any representable number between ``x + spacing(x)`` and
x for any finite x.
Spacing of +- inf and NaN is NaN.
Examples
--------
>>> import numpy as np
>>> np.spacing(1) == np.finfo(np.float64).eps
True
numpy.split
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
split(ary, indices_or_sections, axis=0)
Split an array into multiple sub-arrays as views into `ary`.
Parameters
----------
ary : ndarray
Array to be divided into sub-arrays.
indices_or_sections : int or 1-D array
If `indices_or_sections` is an integer, N, the array will be divided
into N equal arrays along `axis`. If such a split is not possible,
an error is raised.
If `indices_or_sections` is a 1-D array of sorted integers, the entries
indicate where along `axis` the array is split. For example,
``[2, 3]`` would, for ``axis=0``, result in
- ary[:2]
- ary[2:3]
- ary[3:]
If an index exceeds the dimension of the array along `axis`,
an empty sub-array is returned correspondingly.
axis : int, optional
The axis along which to split, default is 0.
Returns
-------
sub-arrays : list of ndarrays
A list of sub-arrays as views into `ary`.
Raises
------
ValueError
If `indices_or_sections` is given as an integer, but
a split does not result in equal division.
See Also
--------
array_split : Split an array into multiple sub-arrays of equal or
near-equal size. Does not raise an exception if
an equal division cannot be made.
hsplit : Split array into multiple sub-arrays horizontally (column-wise).
vsplit : Split array into multiple sub-arrays vertically (row wise).
dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
hstack : Stack arrays in sequence horizontally (column wise).
vstack : Stack arrays in sequence vertically (row wise).
dstack : Stack arrays in sequence depth wise (along third dimension).
Examples
--------
>>> import numpy as np
>>> x = np.arange(9.0)
>>> np.split(x, 3)
[array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])]
>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
[array([0., 1., 2.]),
array([3., 4.]),
array([5.]),
array([6., 7.]),
array([], dtype=float64)]
numpy.sqrt
Python Library Documentation: ufunc
sqrt = <ufunc 'sqrt'>
sqrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the non-negative square-root of an array, element-wise.
Parameters
----------
x : array_like
The values whose square-roots are required.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
An array of the same shape as `x`, containing the positive
square-root of each element in `x`. If any element in `x` is
complex, a complex array is returned (and the square-roots of
negative reals are calculated). If all of the elements in `x`
are real, so is `y`, with negative elements returning ``nan``.
If `out` was provided, `y` is a reference to it.
This is a scalar if `x` is a scalar.
See Also
--------
emath.sqrt
A version which returns complex numbers when given negative reals.
Note that 0.0 and -0.0 are handled differently for complex inputs.
Notes
-----
*sqrt* has--consistent with common convention--as its branch cut the
real "interval" [`-inf`, 0), and is continuous from above on it.
A branch cut is a curve in the complex plane across which a given
complex function fails to be continuous.
Examples
--------
>>> import numpy as np
>>> np.sqrt([1,4,9])
array([ 1., 2., 3.])
>>> np.sqrt([4, -1, -3+4J])
array([ 2.+0.j, 0.+1.j, 1.+2.j])
>>> np.sqrt([4, -1, np.inf])
array([ 2., nan, inf])
numpy.square
Python Library Documentation: ufunc
square = <ufunc 'square'>
square(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the element-wise square of the input.
Parameters
----------
x : array_like
Input data.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Element-wise `x*x`, of the same shape and dtype as `x`.
This is a scalar if `x` is a scalar.
See Also
--------
numpy.linalg.matrix_power
sqrt
power
Examples
--------
>>> import numpy as np
>>> np.square([-1j, 1])
array([-1.-0.j, 1.+0.j])
numpy.squeeze
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
squeeze(a, axis=None)
Remove axes of length one from `a`.
Parameters
----------
a : array_like
Input data.
axis : None or int or tuple of ints, optional
.. versionadded:: 1.7.0
Selects a subset of the entries of length one in the
shape. If an axis is selected with shape entry greater than
one, an error is raised.
Returns
-------
squeezed : ndarray
The input array, but with all or a subset of the
dimensions of length 1 removed. This is always `a` itself
or a view into `a`. Note that if all axes are squeezed,
the result is a 0d array and not a scalar.
Raises
------
ValueError
If `axis` is not None, and an axis being squeezed is not of length 1
See Also
--------
expand_dims : The inverse operation, adding entries of length one
reshape : Insert, remove, and combine dimensions, and resize existing ones
Examples
--------
>>> import numpy as np
>>> x = np.array([[[0], [1], [2]]])
>>> x.shape
(1, 3, 1)
>>> np.squeeze(x).shape
(3,)
>>> np.squeeze(x, axis=0).shape
(3, 1)
>>> np.squeeze(x, axis=1).shape
Traceback (most recent call last):
...
ValueError: cannot select an axis to squeeze out which has size
not equal to one
>>> np.squeeze(x, axis=2).shape
(1, 3)
>>> x = np.array([[1234]])
>>> x.shape
(1, 1)
>>> np.squeeze(x)
array(1234) # 0d array
>>> np.squeeze(x).shape
()
>>> np.squeeze(x)[()]
1234
numpy.stack
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
stack(arrays, axis=0, out=None, *, dtype=None, casting='same_kind')
Join a sequence of arrays along a new axis.
The ``axis`` parameter specifies the index of the new axis in the
dimensions of the result. For example, if ``axis=0`` it will be the first
dimension and if ``axis=-1`` it will be the last dimension.
.. versionadded:: 1.10.0
Parameters
----------
arrays : sequence of array_like
Each array must have the same shape.
axis : int, optional
The axis in the result array along which the input arrays are stacked.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what stack would have returned if no
out argument were specified.
dtype : str or dtype
If provided, the destination array will have this dtype. Cannot be
provided together with `out`.
.. versionadded:: 1.24
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'same_kind'.
.. versionadded:: 1.24
Returns
-------
stacked : ndarray
The stacked array has one more dimension than the input arrays.
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
block : Assemble an nd-array from nested lists of blocks.
split : Split array into a list of multiple sub-arrays of equal size.
unstack : Split an array into a tuple of sub-arrays along an axis.
Examples
--------
>>> import numpy as np
>>> rng = np.random.default_rng()
>>> arrays = [rng.normal(size=(3,4)) for _ in range(10)]
>>> np.stack(arrays, axis=0).shape
(10, 3, 4)
>>> np.stack(arrays, axis=1).shape
(3, 10, 4)
>>> np.stack(arrays, axis=2).shape
(3, 4, 10)
>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.stack((a, b))
array([[1, 2, 3],
[4, 5, 6]])
>>> np.stack((a, b), axis=-1)
array([[1, 4],
[2, 5],
[3, 6]])
numpy.std
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>, mean=<no value>, correction=<no value>)
Compute the standard deviation along the specified axis.
Returns the standard deviation, a measure of the spread of a distribution,
of the array elements. The standard deviation is computed for the
flattened array by default, otherwise over the specified axis.
Parameters
----------
a : array_like
Calculate the standard deviation of these values.
axis : None or int or tuple of ints, optional
Axis or axes along which the standard deviation is computed. The
default is to compute the standard deviation of the flattened array.
.. versionadded:: 1.7.0
If this is a tuple of ints, a standard deviation is performed over
multiple axes, instead of a single axis or all the axes as before.
dtype : dtype, 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.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type (of the calculated
values) will be cast if necessary.
See :ref:`ufuncs-output-type` for more details.
ddof : {int, float}, optional
Means Delta Degrees of Freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of elements.
By default `ddof` is zero. See Notes for details about use of `ddof`.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `std` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
where : array_like of bool, optional
Elements to include in the standard deviation.
See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.20.0
mean : array_like, optional
Provide the mean to prevent its recalculation. The mean should have
a shape as if it was calculated with ``keepdims=True``.
The axis for the calculation of the mean should be the same as used in
the call to this std function.
.. versionadded:: 1.26.0
correction : {int, float}, optional
Array API compatible name for the ``ddof`` parameter. Only one of them
can be provided at the same time.
.. versionadded:: 2.0.0
Returns
-------
standard_deviation : ndarray, see dtype parameter above.
If `out` is None, return a new array containing the standard deviation,
otherwise return a reference to the output array.
See Also
--------
var, mean, nanmean, nanstd, nanvar
:ref:`ufuncs-output-type`
Notes
-----
There are several common variants of the array standard deviation
calculation. Assuming the input `a` is a one-dimensional NumPy array
and ``mean`` is either provided as an argument or computed as
``a.mean()``, NumPy computes the standard deviation of an array as::
N = len(a)
d2 = abs(a - mean)**2 # abs is for complex `a`
var = d2.sum() / (N - ddof) # note use of `ddof`
std = var**0.5
Different values of the argument `ddof` are useful in different
contexts. NumPy's default ``ddof=0`` corresponds with the expression:
.. math::
\sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N}}
which is sometimes called the "population standard deviation" in the field
of statistics because it applies the definition of standard deviation to
`a` as if `a` were a complete population of possible observations.
Many other libraries define the standard deviation of an array
differently, e.g.:
.. math::
\sqrt{\frac{\sum_i{|a_i - \bar{a}|^2 }}{N - 1}}
In statistics, the resulting quantity is sometimed called the "sample
standard deviation" because if `a` is a random sample from a larger
population, this calculation provides the square root of an unbiased
estimate of the variance of the population. The use of :math:`N-1` in the
denominator is often called "Bessel's correction" because it corrects for
bias (toward lower values) in the variance estimate introduced when the
sample mean of `a` is used in place of the true mean of the population.
The resulting estimate of the standard deviation is still biased, but less
than it would have been without the correction. For this quantity, use
``ddof=1``.
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 standard deviation 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
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> np.std(a)
1.1180339887498949 # may vary
>>> np.std(a, axis=0)
array([1., 1.])
>>> np.std(a, axis=1)
array([0.5, 0.5])
In single precision, std() can be inaccurate:
>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.std(a)
0.45000005
Computing the standard deviation in float64 is more accurate:
>>> np.std(a, dtype=np.float64)
0.44999999925494177 # may vary
Specifying a where argument:
>>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
>>> np.std(a)
2.614064523559687 # may vary
>>> np.std(a, where=[[True], [True], [False]])
2.0
Using the mean keyword to save computation time:
>>> import numpy as np
>>> from timeit import timeit
>>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
>>> mean = np.mean(a, axis=1, keepdims=True)
>>>
>>> g = globals()
>>> n = 10000
>>> t1 = timeit("std = np.std(a, axis=1, mean=mean)", globals=g, number=n)
>>> t2 = timeit("std = np.std(a, axis=1)", globals=g, number=n)
>>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
#doctest: +SKIP
Percentage execution time saved 30%
numpy.str_
Python Library Documentation: class str_ in module numpy
class str_(builtins.str, character)
| A unicode string.
|
| This type strips trailing null codepoints.
|
| >>> s = np.str_("abc\x00")
| >>> s
| 'abc'
|
| Unlike the builtin :class:`str`, this supports the
| :ref:`python:bufferobjects`, exposing its contents as UCS4:
|
| >>> m = memoryview(np.str_("abc"))
| >>> m.format
| '3w'
| >>> m.tobytes()
| b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'
|
| :Character code: ``'U'``
|
| Method resolution order:
| str_
| builtins.str
| character
| flexible
| generic
| builtins.object
|
| Methods defined here:
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __str__(self, /)
| Return str(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.str:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by format_spec.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __iter__(self, /)
| Implement iter(self).
|
| __len__(self, /)
| Return len(self).
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.str:
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __abs__(self, /)
| abs(self)
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __bool__(self, /)
| True if self else False
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| Helper for pickle.
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setstate__(...)
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| base
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.base`.
|
| data
| Pointer to start of data.
|
| device
|
| dtype
| Get array data-descriptor.
|
| flags
| The integer value of flags.
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
numpy.strings
Python Library Documentation: package numpy.strings in numpy
NAME
numpy.strings
DESCRIPTION
This module contains a set of functions for vectorized string
operations.
PACKAGE CONTENTS
FUNCTIONS
capitalize(a)
Return a copy of ``a`` with only the first character of each element
capitalized.
Calls :meth:`str.capitalize` element-wise.
For byte strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array of strings to capitalize.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.capitalize
Examples
--------
>>> import numpy as np
>>> c = np.array(['a1b2','1b2a','b2a1','2a1b'],'S4'); c
array(['a1b2', '1b2a', 'b2a1', '2a1b'],
dtype='|S4')
>>> np.strings.capitalize(c)
array(['A1b2', '1b2a', 'B2a1', '2a1b'],
dtype='|S4')
center(a, width, fillchar=' ')
Return a copy of `a` with its elements centered in a string of
length `width`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
width : array_like, with any integer dtype
The length of the resulting strings, unless ``width < str_len(a)``.
fillchar : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Optional padding character to use (default is space).
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.center
Notes
-----
While it is possible for ``a`` and ``fillchar`` to have different dtypes,
passing a non-ASCII character in ``fillchar`` when ``a`` is of dtype "S"
is not allowed, and a ``ValueError`` is raised.
Examples
--------
>>> import numpy as np
>>> c = np.array(['a1b2','1b2a','b2a1','2a1b']); c
array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4')
>>> np.strings.center(c, width=9)
array([' a1b2 ', ' 1b2a ', ' b2a1 ', ' 2a1b '], dtype='<U9')
>>> np.strings.center(c, width=9, fillchar='*')
array(['***a1b2**', '***1b2a**', '***b2a1**', '***2a1b**'], dtype='<U9')
>>> np.strings.center(c, width=1)
array(['a1b2', '1b2a', 'b2a1', '2a1b'], dtype='<U4')
count(a, sub, start=0, end=None)
Returns an array with the number of non-overlapping occurrences of
substring ``sub`` in the range [``start``, ``end``).
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
The substring to search for.
start, end : array_like, with any integer dtype
The range to look in, interpreted as in slice notation.
Returns
-------
y : ndarray
Output array of ints
See Also
--------
str.count
Examples
--------
>>> import numpy as np
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.count(c, 'A')
array([3, 1, 1])
>>> np.strings.count(c, 'aA')
array([3, 1, 0])
>>> np.strings.count(c, 'A', start=1, end=4)
array([2, 1, 1])
>>> np.strings.count(c, 'A', start=1, end=3)
array([1, 0, 0])
decode(a, encoding=None, errors=None)
Calls :meth:`bytes.decode` element-wise.
The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the
:mod:`codecs` module.
Parameters
----------
a : array_like, with ``bytes_`` dtype
encoding : str, optional
The name of an encoding
errors : str, optional
Specifies how to handle encoding errors
Returns
-------
out : ndarray
See Also
--------
:py:meth:`bytes.decode`
Notes
-----
The type of the result will depend on the encoding specified.
Examples
--------
>>> import numpy as np
>>> c = np.array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
... b'\x81\x82\xc2\xc1\xc2\x82\x81'])
>>> c
array([b'\x81\xc1\x81\xc1\x81\xc1', b'@@\x81\xc1@@',
b'\x81\x82\xc2\xc1\xc2\x82\x81'], dtype='|S7')
>>> np.strings.decode(c, encoding='cp037')
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
encode(a, encoding=None, errors=None)
Calls :meth:`str.encode` element-wise.
The set of available codecs comes from the Python standard library,
and may be extended at runtime. For more information, see the
:mod:`codecs` module.
Parameters
----------
a : array_like, with ``StringDType`` or ``str_`` dtype
encoding : str, optional
The name of an encoding
errors : str, optional
Specifies how to handle encoding errors
Returns
-------
out : ndarray
See Also
--------
str.encode
Notes
-----
The type of the result will depend on the encoding specified.
Examples
--------
>>> import numpy as np
>>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.strings.encode(a, encoding='cp037')
array([b'ÁÁÁ', b'@@Á@@',
b'ÂÁÂ'], dtype='|S7')
endswith(a, suffix, start=0, end=None)
Returns a boolean array which is `True` where the string element
in ``a`` ends with ``suffix``, otherwise `False`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
suffix : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
start, end : array_like, with any integer dtype
With ``start``, test beginning at that position. With ``end``,
stop comparing at that position.
Returns
-------
out : ndarray
Output array of bools
See Also
--------
str.endswith
Examples
--------
>>> import numpy as np
>>> s = np.array(['foo', 'bar'])
>>> s
array(['foo', 'bar'], dtype='<U3')
>>> np.strings.endswith(s, 'ar')
array([False, True])
>>> np.strings.endswith(s, 'a', start=1, end=2)
array([False, True])
expandtabs(a, tabsize=8)
Return a copy of each string element where all tab characters are
replaced by one or more spaces.
Calls :meth:`str.expandtabs` element-wise.
Return a copy of each string element where all tab characters are
replaced by one or more spaces, depending on the current column
and the given `tabsize`. The column number is reset to zero after
each newline occurring in the string. This doesn't understand other
non-printing characters or escape sequences.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array
tabsize : int, optional
Replace tabs with `tabsize` number of spaces. If not given defaults
to 8 spaces.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input type
See Also
--------
str.expandtabs
Examples
--------
>>> import numpy as np
>>> a = np.array([' Hello world'])
>>> np.strings.expandtabs(a, tabsize=4) # doctest: +SKIP
array([' Hello world'], dtype='<U21') # doctest: +SKIP
find(a, sub, start=0, end=None)
For each element, return the lowest index in the string where
substring ``sub`` is found, such that ``sub`` is contained in the
range [``start``, ``end``).
Parameters
----------
a : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
sub : array_like, with `np.bytes_` or `np.str_` dtype
The substring to search for.
start, end : array_like, with any integer dtype
The range to look in, interpreted as in slice notation.
Returns
-------
y : ndarray
Output array of ints
See Also
--------
str.find
Examples
--------
>>> import numpy as np
>>> a = np.array(["NumPy is a Python library"])
>>> np.strings.find(a, "Python")
array([11])
index(a, sub, start=0, end=None)
Like `find`, but raises :exc:`ValueError` when the substring is not found.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
start, end : array_like, with any integer dtype, optional
Returns
-------
out : ndarray
Output array of ints.
See Also
--------
find, str.index
Examples
--------
>>> import numpy as np
>>> a = np.array(["Computer Science"])
>>> np.strings.index(a, "Science", start=0, end=None)
array([9])
ljust(a, width, fillchar=' ')
Return an array with the elements of `a` left-justified in a
string of length `width`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
width : array_like, with any integer dtype
The length of the resulting strings, unless ``width < str_len(a)``.
fillchar : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Optional character to use for padding (default is space).
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.ljust
Notes
-----
While it is possible for ``a`` and ``fillchar`` to have different dtypes,
passing a non-ASCII character in ``fillchar`` when ``a`` is of dtype "S"
is not allowed, and a ``ValueError`` is raised.
Examples
--------
>>> import numpy as np
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.strings.ljust(c, width=3)
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.ljust(c, width=9)
array(['aAaAaA ', ' aA ', 'abBABba '], dtype='<U9')
lower(a)
Return an array with the elements converted to lowercase.
Call :meth:`str.lower` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.lower
Examples
--------
>>> import numpy as np
>>> c = np.array(['A1B C', '1BCA', 'BCA1']); c
array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
>>> np.strings.lower(c)
array(['a1b c', '1bca', 'bca1'], dtype='<U5')
lstrip(a, chars=None)
For each element in `a`, return a copy with the leading characters
removed.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
chars : scalar with the same dtype as ``a``, optional
The ``chars`` argument is a string specifying the set of
characters to be removed. If ``None``, the ``chars``
argument defaults to removing whitespace. The ``chars`` argument
is not a prefix or suffix; rather, all combinations of its
values are stripped.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.lstrip
Examples
--------
>>> import numpy as np
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
# The 'a' variable is unstripped from c[1] because of leading whitespace.
>>> np.strings.lstrip(c, 'a')
array(['AaAaA', ' aA ', 'bBABba'], dtype='<U7')
>>> np.strings.lstrip(c, 'A') # leaves c unchanged
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> (np.strings.lstrip(c, ' ') == np.strings.lstrip(c, '')).all()
np.False_
>>> (np.strings.lstrip(c, ' ') == np.strings.lstrip(c)).all()
np.True_
mod(a, values)
Return (a % i), that is pre-Python 2.6 string formatting
(interpolation), element-wise for a pair of array_likes of str
or unicode.
Parameters
----------
a : array_like, with `np.bytes_` or `np.str_` dtype
values : array_like of values
These values will be element-wise interpolated into the string.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
Examples
--------
>>> import numpy as np
>>> a = np.array(["NumPy is a %s library"])
>>> np.strings.mod(a, values=["Python"])
array(['NumPy is a Python library'], dtype='<U25')
>>> a = np.array([b'%d bytes', b'%d bits'])
>>> values = np.array([8, 64])
>>> np.strings.mod(a, values)
array([b'8 bytes', b'64 bits'], dtype='|S7')
multiply(a, i)
Return (a * i), that is string multiple concatenation,
element-wise.
Values in ``i`` of less than 0 are treated as 0 (which yields an
empty string).
Parameters
----------
a : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
i : array_like, with any integer dtype
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
Examples
--------
>>> import numpy as np
>>> a = np.array(["a", "b", "c"])
>>> np.strings.multiply(a, 3)
array(['aaa', 'bbb', 'ccc'], dtype='<U3')
>>> i = np.array([1, 2, 3])
>>> np.strings.multiply(a, i)
array(['a', 'bb', 'ccc'], dtype='<U3')
>>> np.strings.multiply(np.array(['a']), i)
array(['a', 'aa', 'aaa'], dtype='<U3')
>>> a = np.array(['a', 'b', 'c', 'd', 'e', 'f']).reshape((2, 3))
>>> np.strings.multiply(a, 3)
array([['aaa', 'bbb', 'ccc'],
['ddd', 'eee', 'fff']], dtype='<U3')
>>> np.strings.multiply(a, i)
array([['a', 'bb', 'ccc'],
['d', 'ee', 'fff']], dtype='<U3')
partition(a, sep)
Partition each element in ``a`` around ``sep``.
For each element in ``a``, split the element at the first
occurrence of ``sep``, and return a 3-tuple containing the part
before the separator, the separator itself, and the part after
the separator. If the separator is not found, the first item of
the tuple will contain the whole string, and the second and third
ones will be the empty string.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array
sep : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Separator to split each string element in ``a``.
Returns
-------
out : 3-tuple:
- array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
part before the separator
- array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
separator
- array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
part after the separator
See Also
--------
str.partition
Examples
--------
>>> import numpy as np
>>> x = np.array(["Numpy is nice!"])
>>> np.strings.partition(x, " ")
(array(['Numpy'], dtype='<U5'),
array([' '], dtype='<U1'),
array(['is nice!'], dtype='<U8'))
replace(a, old, new, count=-1)
For each element in ``a``, return a copy of the string with
occurrences of substring ``old`` replaced by ``new``.
Parameters
----------
a : array_like, with ``bytes_`` or ``str_`` dtype
old, new : array_like, with ``bytes_`` or ``str_`` dtype
count : array_like, with ``int_`` dtype
If the optional argument ``count`` is given, only the first
``count`` occurrences are replaced.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.replace
Examples
--------
>>> import numpy as np
>>> a = np.array(["That is a mango", "Monkeys eat mangos"])
>>> np.strings.replace(a, 'mango', 'banana')
array(['That is a banana', 'Monkeys eat bananas'], dtype='<U19')
>>> a = np.array(["The dish is fresh", "This is it"])
>>> np.strings.replace(a, 'is', 'was')
array(['The dwash was fresh', 'Thwas was it'], dtype='<U19')
rfind(a, sub, start=0, end=None)
For each element, return the highest index in the string where
substring ``sub`` is found, such that ``sub`` is contained in the
range [``start``, ``end``).
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
sub : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
The substring to search for.
start, end : array_like, with any integer dtype
The range to look in, interpreted as in slice notation.
Returns
-------
y : ndarray
Output array of ints
See Also
--------
str.rfind
Examples
--------
>>> import numpy as np
>>> a = np.array(["Computer Science"])
>>> np.strings.rfind(a, "Science", start=0, end=None)
array([9])
>>> np.strings.rfind(a, "Science", start=0, end=8)
array([-1])
>>> b = np.array(["Computer Science", "Science"])
>>> np.strings.rfind(b, "Science", start=0, end=None)
array([9, 0])
rindex(a, sub, start=0, end=None)
Like `rfind`, but raises :exc:`ValueError` when the substring `sub` is
not found.
Parameters
----------
a : array-like, with `np.bytes_` or `np.str_` dtype
sub : array-like, with `np.bytes_` or `np.str_` dtype
start, end : array-like, with any integer dtype, optional
Returns
-------
out : ndarray
Output array of ints.
See Also
--------
rfind, str.rindex
Examples
--------
>>> a = np.array(["Computer Science"])
>>> np.strings.rindex(a, "Science", start=0, end=None)
array([9])
rjust(a, width, fillchar=' ')
Return an array with the elements of `a` right-justified in a
string of length `width`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
width : array_like, with any integer dtype
The length of the resulting strings, unless ``width < str_len(a)``.
fillchar : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Optional padding character to use (default is space).
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.rjust
Notes
-----
While it is possible for ``a`` and ``fillchar`` to have different dtypes,
passing a non-ASCII character in ``fillchar`` when ``a`` is of dtype "S"
is not allowed, and a ``ValueError`` is raised.
Examples
--------
>>> import numpy as np
>>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.strings.rjust(a, width=3)
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.rjust(a, width=9)
array([' aAaAaA', ' aA ', ' abBABba'], dtype='<U9')
rpartition(a, sep)
Partition (split) each element around the right-most separator.
For each element in ``a``, split the element at the last
occurrence of ``sep``, and return a 3-tuple containing the part
before the separator, the separator itself, and the part after
the separator. If the separator is not found, the third item of
the tuple will contain the whole string, and the first and second
ones will be the empty string.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array
sep : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Separator to split each string element in ``a``.
Returns
-------
out : 3-tuple:
- array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
part before the separator
- array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
separator
- array with ``StringDType``, ``bytes_`` or ``str_`` dtype with the
part after the separator
See Also
--------
str.rpartition
Examples
--------
>>> import numpy as np
>>> a = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> np.strings.rpartition(a, 'A')
(array(['aAaAa', ' a', 'abB'], dtype='<U5'),
array(['A', 'A', 'A'], dtype='<U1'),
array(['', ' ', 'Bba'], dtype='<U3'))
rstrip(a, chars=None)
For each element in `a`, return a copy with the trailing characters
removed.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
chars : scalar with the same dtype as ``a``, optional
The ``chars`` argument is a string specifying the set of
characters to be removed. If ``None``, the ``chars``
argument defaults to removing whitespace. The ``chars`` argument
is not a prefix or suffix; rather, all combinations of its
values are stripped.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.rstrip
Examples
--------
>>> import numpy as np
>>> c = np.array(['aAaAaA', 'abBABba'])
>>> c
array(['aAaAaA', 'abBABba'], dtype='<U7')
>>> np.strings.rstrip(c, 'a')
array(['aAaAaA', 'abBABb'], dtype='<U7')
>>> np.strings.rstrip(c, 'A')
array(['aAaAa', 'abBABba'], dtype='<U7')
startswith(a, prefix, start=0, end=None)
Returns a boolean array which is `True` where the string element
in ``a`` starts with ``prefix``, otherwise `False`.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
prefix : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
start, end : array_like, with any integer dtype
With ``start``, test beginning at that position. With ``end``,
stop comparing at that position.
Returns
-------
out : ndarray
Output array of bools
See Also
--------
str.startswith
Examples
--------
>>> import numpy as np
>>> s = np.array(['foo', 'bar'])
>>> s
array(['foo', 'bar'], dtype='<U3')
>>> np.strings.startswith(s, 'fo')
array([True, False])
>>> np.strings.startswith(s, 'o', start=1, end=2)
array([True, False])
strip(a, chars=None)
For each element in `a`, return a copy with the leading and
trailing characters removed.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
chars : scalar with the same dtype as ``a``, optional
The ``chars`` argument is a string specifying the set of
characters to be removed. If ``None``, the ``chars``
argument defaults to removing whitespace. The ``chars`` argument
is not a prefix or suffix; rather, all combinations of its
values are stripped.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.strip
Examples
--------
>>> import numpy as np
>>> c = np.array(['aAaAaA', ' aA ', 'abBABba'])
>>> c
array(['aAaAaA', ' aA ', 'abBABba'], dtype='<U7')
>>> np.strings.strip(c)
array(['aAaAaA', 'aA', 'abBABba'], dtype='<U7')
# 'a' unstripped from c[1] because of leading whitespace.
>>> np.strings.strip(c, 'a')
array(['AaAaA', ' aA ', 'bBABb'], dtype='<U7')
# 'A' unstripped from c[1] because of trailing whitespace.
>>> np.strings.strip(c, 'A')
array(['aAaAa', ' aA ', 'abBABba'], dtype='<U7')
swapcase(a)
Return element-wise a copy of the string with
uppercase characters converted to lowercase and vice versa.
Calls :meth:`str.swapcase` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.swapcase
Examples
--------
>>> import numpy as np
>>> c=np.array(['a1B c','1b Ca','b Ca1','cA1b'],'S5'); c
array(['a1B c', '1b Ca', 'b Ca1', 'cA1b'],
dtype='|S5')
>>> np.strings.swapcase(c)
array(['A1b C', '1B cA', 'B cA1', 'Ca1B'],
dtype='|S5')
title(a)
Return element-wise title cased version of string or unicode.
Title case words start with uppercase characters, all remaining cased
characters are lowercase.
Calls :meth:`str.title` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.title
Examples
--------
>>> import numpy as np
>>> c=np.array(['a1b c','1b ca','b ca1','ca1b'],'S5'); c
array(['a1b c', '1b ca', 'b ca1', 'ca1b'],
dtype='|S5')
>>> np.strings.title(c)
array(['A1B C', '1B Ca', 'B Ca1', 'Ca1B'],
dtype='|S5')
translate(a, table, deletechars=None)
For each element in `a`, return a copy of the string where all
characters occurring in the optional argument `deletechars` are
removed, and the remaining characters have been mapped through the
given translation table.
Calls :meth:`str.translate` element-wise.
Parameters
----------
a : array-like, with `np.bytes_` or `np.str_` dtype
table : str of length 256
deletechars : str
Returns
-------
out : ndarray
Output array of str or unicode, depending on input type
See Also
--------
str.translate
Examples
--------
>>> import numpy as np
>>> a = np.array(['a1b c', '1bca', 'bca1'])
>>> table = a[0].maketrans('abc', '123')
>>> deletechars = ' '
>>> np.char.translate(a, table, deletechars)
array(['112 3', '1231', '2311'], dtype='<U5')
upper(a)
Return an array with the elements converted to uppercase.
Calls :meth:`str.upper` element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
Input array.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input types
See Also
--------
str.upper
Examples
--------
>>> import numpy as np
>>> c = np.array(['a1b c', '1bca', 'bca1']); c
array(['a1b c', '1bca', 'bca1'], dtype='<U5')
>>> np.strings.upper(c)
array(['A1B C', '1BCA', 'BCA1'], dtype='<U5')
zfill(a, width)
Return the numeric string left-filled with zeros. A leading
sign prefix (``+``/``-``) is handled by inserting the padding
after the sign character rather than before.
Parameters
----------
a : array-like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
width : array_like, with any integer dtype
Width of string to left-fill elements in `a`.
Returns
-------
out : ndarray
Output array of ``StringDType``, ``bytes_`` or ``str_`` dtype,
depending on input type
See Also
--------
str.zfill
Examples
--------
>>> import numpy as np
>>> np.strings.zfill(['1', '-1', '+1'], 3)
array(['001', '-01', '+01'], dtype='<U3')
DATA
__all__ = ['equal', 'not_equal', 'less', 'less_equal', 'greater', 'gre...
add = <ufunc 'add'>
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
add : ndarray or scalar
The sum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.
Examples
--------
>>> import numpy as np
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
The ``+`` operator can be used as a shorthand for ``np.add`` on ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 + x2
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
equal = <ufunc 'equal'>
equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return (x1 == x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray or scalar
Output array, element-wise comparison of `x1` and `x2`.
Typically of type bool, unless ``dtype=object`` is passed.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
not_equal, greater_equal, less_equal, greater, less
Examples
--------
>>> import numpy as np
>>> np.equal([0, 1, 3], np.arange(3))
array([ True, True, False])
What is compared are values, not types. So an int (1) and an array of
length one can evaluate as True:
>>> np.equal(1, np.ones(1))
array([ True])
The ``==`` operator can be used as a shorthand for ``np.equal`` on
ndarrays.
>>> a = np.array([2, 4, 6])
>>> b = np.array([2, 4, 2])
>>> a == b
array([ True, True, False])
greater = <ufunc 'greater'>
greater(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 > x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
greater_equal, less, less_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.greater([4,2],[2,2])
array([ True, False])
The ``>`` operator can be used as a shorthand for ``np.greater`` on
ndarrays.
>>> a = np.array([4, 2])
>>> b = np.array([2, 2])
>>> a > b
array([ True, False])
greater_equal = <ufunc 'greater_equal'>
greater_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 >= x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : bool or ndarray of bool
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
--------
greater, less, less_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.greater_equal([4, 2, 1], [2, 2, 2])
array([ True, True, False])
The ``>=`` operator can be used as a shorthand for ``np.greater_equal``
on ndarrays.
>>> a = np.array([4, 2, 1])
>>> b = np.array([2, 2, 2])
>>> a >= b
array([ True, True, False])
isalnum = <ufunc 'isalnum'>
isalnum(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if all characters in the string are
alphanumeric and there is at least one character, false otherwise.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray
Output array of bool
This is a scalar if `x` is a scalar.
See Also
--------
str.isalnum
Examples
--------
>>> import numpy as np
>>> a = np.array(['a', '1', 'a1', '(', ''])
>>> np.strings.isalnum(a)
array([ True, True, True, False, False])
isalpha = <ufunc 'isalpha'>
isalpha(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if all characters in the data
interpreted as a string are alphabetic and there is at least
one character, false otherwise.
For byte strings (i.e. ``bytes``), alphabetic characters are
those byte values in the sequence
b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. For
Unicode strings, alphabetic characters are those characters
defined in the Unicode character database as “Letter”.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isalpha
Examples
--------
>>> import numpy as np
>>> a = np.array(['a', 'b', '0'])
>>> np.strings.isalpha(a)
array([ True, True, False])
>>> a = np.array([['a', 'b', '0'], ['c', '1', '2']])
>>> np.strings.isalpha(a)
array([[ True, True, False], [ True, False, False]])
isdecimal = <ufunc 'isdecimal'>
isdecimal(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
For each element, return True if there are only decimal
characters in the element.
Decimal characters include digit characters, and all characters
that can be used to form decimal-radix numbers,
e.g. ``U+0660, ARABIC-INDIC DIGIT ZERO``.
Parameters
----------
x : array_like, with ``StringDType`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isdecimal
Examples
--------
>>> import numpy as np
>>> np.strings.isdecimal(['12345', '4.99', '123ABC', ''])
array([ True, False, False, False])
isdigit = <ufunc 'isdigit'>
isdigit(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if all characters in the string are
digits and there is at least one character, false otherwise.
For byte strings, digits are the byte values in the sequence
b'0123456789'. For Unicode strings, digits include decimal
characters and digits that need special handling, such as the
compatibility superscript digits. This also covers digits which
cannot be used to form numbers in base 10, like the Kharosthi numbers.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isdigit
Examples
--------
>>> import numpy as np
>>> a = np.array(['a', 'b', '0'])
>>> np.strings.isdigit(a)
array([False, False, True])
>>> a = np.array([['a', 'b', '0'], ['c', '1', '2']])
>>> np.strings.isdigit(a)
array([[False, False, True], [False, True, True]])
islower = <ufunc 'islower'>
islower(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if all cased characters in the
string are lowercase and there is at least one cased character,
false otherwise.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.islower
Examples
--------
>>> import numpy as np
>>> np.strings.islower("GHC")
array(False)
>>> np.strings.islower("ghc")
array(True)
isnumeric = <ufunc 'isnumeric'>
isnumeric(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
For each element, return True if there are only numeric
characters in the element.
Numeric characters include digit characters, and all characters
that have the Unicode numeric value property, e.g. ``U+2155,
VULGAR FRACTION ONE FIFTH``.
Parameters
----------
x : array_like, with ``StringDType`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isnumeric
Examples
--------
>>> import numpy as np
>>> np.strings.isnumeric(['123', '123abc', '9.0', '1/4', 'VIII'])
array([ True, False, False, False, False])
isspace = <ufunc 'isspace'>
isspace(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if there are only whitespace
characters in the string and there is at least one character,
false otherwise.
For byte strings, whitespace characters are the ones in the
sequence b' \t\n\r\x0b\f'. For Unicode strings, a character is
whitespace, if, in the Unicode character database, its general
category is Zs (“Separator, space”), or its bidirectional class
is one of WS, B, or S.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isspace
istitle = <ufunc 'istitle'>
istitle(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns true for each element if the element is a titlecased
string and there is at least one character, false otherwise.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.istitle
Examples
--------
>>> import numpy as np
>>> np.strings.istitle("Numpy Is Great")
array(True)
>>> np.strings.istitle("Numpy is great")
array(False)
isupper = <ufunc 'isupper'>
isupper(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return true for each element if all cased characters in the
string are uppercase and there is at least one character, false
otherwise.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_`` or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray
Output array of bools
This is a scalar if `x` is a scalar.
See Also
--------
str.isupper
Examples
--------
>>> import numpy as np
>>> np.strings.isupper("GHC")
array(True)
>>> a = np.array(["hello", "HELLO", "Hello"])
>>> np.strings.isupper(a)
array([False, True, False])
less = <ufunc 'less'>
less(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 < x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
greater, less_equal, greater_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.less([1, 2], [2, 2])
array([ True, False])
The ``<`` operator can be used as a shorthand for ``np.less`` on ndarrays.
>>> a = np.array([1, 2])
>>> b = np.array([2, 2])
>>> a < b
array([ True, False])
less_equal = <ufunc 'less_equal'>
less_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truth value of (x1 <= x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
greater, less, greater_equal, equal, not_equal
Examples
--------
>>> import numpy as np
>>> np.less_equal([4, 2, 1], [2, 2, 2])
array([False, True, True])
The ``<=`` operator can be used as a shorthand for ``np.less_equal`` on
ndarrays.
>>> a = np.array([4, 2, 1])
>>> b = np.array([2, 2, 2])
>>> a <= b
array([False, True, True])
not_equal = <ufunc 'not_equal'>
not_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return (x1 != x2) element-wise.
Parameters
----------
x1, x2 : array_like
Input arrays.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
out : ndarray 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
--------
>>> import numpy as np
>>> 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])
str_len = <ufunc 'str_len'>
str_len(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Returns the length of each element. For byte strings,
this is the number of bytes, while, for Unicode strings,
it is the number of Unicode code points.
Parameters
----------
x : array_like, with ``StringDType``, ``bytes_``, or ``str_`` dtype
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
Output array of ints
This is a scalar if `x` is a scalar.
See Also
--------
len
Examples
--------
>>> import numpy as np
>>> a = np.array(['Grace Hopper Conference', 'Open Source Day'])
>>> np.strings.str_len(a)
array([23, 15])
>>> a = np.array(['Р', 'о'])
>>> np.strings.str_len(a)
array([1, 1])
>>> a = np.array([['hello', 'world'], ['Р', 'о']])
>>> np.strings.str_len(a)
array([[5, 5], [1, 1]])
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\strings\__init__.py
numpy.subtract
Python Library Documentation: ufunc
subtract = <ufunc 'subtract'>
subtract(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Subtract arguments, element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be subtracted from each other.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The difference of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to ``x1 - x2`` in terms of array broadcasting.
Examples
--------
>>> import numpy as np
>>> np.subtract(1.0, 4.0)
-3.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.subtract(x1, x2)
array([[ 0., 0., 0.],
[ 3., 3., 3.],
[ 6., 6., 6.]])
The ``-`` operator can be used as a shorthand for ``np.subtract`` on
ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 - x2
array([[0., 0., 0.],
[3., 3., 3.],
[6., 6., 6.]])
numpy.sum
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
Sum of array elements over a given axis.
Parameters
----------
a : array_like
Elements to sum.
axis : None or int or tuple of ints, optional
Axis or axes along which a sum is performed. The default,
axis=None, will sum all of the elements of the input array. If
axis is negative it counts from the last to the first axis.
.. versionadded:: 1.7.0
If axis is a tuple of ints, a sum is performed on all of the axes
specified in the tuple instead of a single axis or all the axes as
before.
dtype : dtype, optional
The type of the returned array and of the accumulator in which the
elements are summed. The dtype of `a` is used by default unless `a`
has an integer dtype of less precision than the default platform
integer. In that case, if `a` is signed then the platform integer
is used while if `a` is unsigned then an unsigned integer of the
same precision as the platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output, but the type of the output
values will be cast if necessary.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `sum` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
initial : scalar, optional
Starting value for the sum. See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.15.0
where : array_like of bool, optional
Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
.. versionadded:: 1.17.0
Returns
-------
sum_along_axis : ndarray
An array with the same shape as `a`, with the specified
axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar
is returned. If an output array is specified, a reference to
`out` is returned.
See Also
--------
ndarray.sum : Equivalent method.
add: ``numpy.add.reduce`` equivalent function.
cumsum : Cumulative sum of array elements.
trapezoid : Integration of array values using composite trapezoidal rule.
mean, average
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.
The sum of an empty array is the neutral element 0:
>>> np.sum([])
0.0
For floating point numbers the numerical precision of sum (and
``np.add.reduce``) is in general limited by directly adding each number
individually to the result causing rounding errors in every step.
However, often numpy will use a numerically better approach (partial
pairwise summation) leading to improved precision in many use-cases.
This improved precision is always provided when no ``axis`` is given.
When ``axis`` is given, it will depend on which axis is summed.
Technically, to provide the best speed possible, the improved precision
is only used when the summation is along the fast axis in memory.
Note that the exact precision may vary depending on other parameters.
In contrast to NumPy, Python's ``math.fsum`` function uses a slower but
more precise approach to summation.
Especially when summing a large number of lower precision floating point
numbers, such as ``float32``, numerical errors can become significant.
In such cases it can be advisable to use `dtype="float64"` to use a higher
precision for the output.
Examples
--------
>>> import numpy as np
>>> np.sum([0.5, 1.5])
2.0
>>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32)
1
>>> np.sum([[0, 1], [0, 5]])
6
>>> np.sum([[0, 1], [0, 5]], axis=0)
array([0, 6])
>>> np.sum([[0, 1], [0, 5]], axis=1)
array([1, 5])
>>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1)
array([1., 5.])
If the accumulator is too small, overflow occurs:
>>> np.ones(128, dtype=np.int8).sum(dtype=np.int8)
-128
You can also start the sum with a value other than zero:
>>> np.sum([10], initial=5)
15
numpy.swapaxes
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
swapaxes(a, axis1, axis2)
Interchange two axes of an array.
Parameters
----------
a : array_like
Input array.
axis1 : int
First axis.
axis2 : int
Second axis.
Returns
-------
a_swapped : ndarray
For NumPy >= 1.10.0, if `a` is an ndarray, then a view of `a` is
returned; otherwise a new array is created. For earlier NumPy
versions a view of `a` is returned only if the order of the
axes is changed, otherwise the input array is returned.
Examples
--------
>>> import numpy as np
>>> x = np.array([[1,2,3]])
>>> np.swapaxes(x,0,1)
array([[1],
[2],
[3]])
>>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
>>> x
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.swapaxes(x,0,2)
array([[[0, 4],
[2, 6]],
[[1, 5],
[3, 7]]])
numpy.take
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
take(a, indices, axis=None, out=None, mode='raise')
Take elements from an array along an axis.
When axis is not None, this function does the same thing as "fancy"
indexing (indexing arrays using arrays); however, it can be easier to use
if you need elements along a given axis. A call such as
``np.take(arr, indices, axis=3)`` is equivalent to
``arr[:,:,:,indices,...]``.
Explained without fancy indexing, this is equivalent to the following use
of `ndindex`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of
indices::
Ni, Nk = a.shape[:axis], a.shape[axis+1:]
Nj = indices.shape
for ii in ndindex(Ni):
for jj in ndindex(Nj):
for kk in ndindex(Nk):
out[ii + jj + kk] = a[ii + (indices[jj],) + kk]
Parameters
----------
a : array_like (Ni..., M, Nk...)
The source array.
indices : array_like (Nj...)
The indices of the values to extract.
.. versionadded:: 1.8.0
Also allow scalars for indices.
axis : int, optional
The axis over which to select values. By default, the flattened
input array is used.
out : ndarray, optional (Ni..., Nj..., Nk...)
If provided, the result will be placed in this array. It should
be of the appropriate shape and dtype. Note that `out` is always
buffered if `mode='raise'`; use other modes for better performance.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
* 'raise' -- raise an error (default)
* 'wrap' -- wrap around
* 'clip' -- clip to the range
'clip' mode means that all indices that are too large are replaced
by the index that addresses the last element along that axis. Note
that this disables indexing with negative numbers.
Returns
-------
out : ndarray (Ni..., Nj..., Nk...)
The returned array has the same type as `a`.
See Also
--------
compress : Take elements using a boolean mask
ndarray.take : equivalent method
take_along_axis : Take elements by matching the array and the index arrays
Notes
-----
By eliminating the inner loop in the description above, and using `s_` to
build simple slice objects, `take` can be expressed in terms of applying
fancy indexing to each 1-d slice::
Ni, Nk = a.shape[:axis], a.shape[axis+1:]
for ii in ndindex(Ni):
for kk in ndindex(Nj):
out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices]
For this reason, it is equivalent to (but faster than) the following use
of `apply_along_axis`::
out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a)
Examples
--------
>>> import numpy as np
>>> a = [4, 3, 5, 7, 6, 8]
>>> indices = [0, 1, 4]
>>> np.take(a, indices)
array([4, 3, 6])
In this example if `a` is an ndarray, "fancy" indexing can be used.
>>> a = np.array(a)
>>> a[indices]
array([4, 3, 6])
If `indices` is not one dimensional, the output also has these dimensions.
>>> np.take(a, [[0, 1], [2, 3]])
array([[4, 3],
[5, 7]])
numpy.take_along_axis
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
take_along_axis(arr, indices, axis)
Take values from the input array by matching 1d index and data slices.
This iterates over matching 1d slices oriented along the specified axis in
the index and data arrays, and uses the former to look up values in the
latter. These slices can be different lengths.
Functions returning an index along an axis, like `argsort` and
`argpartition`, produce suitable indices for this function.
.. versionadded:: 1.15.0
Parameters
----------
arr : ndarray (Ni..., M, Nk...)
Source array
indices : ndarray (Ni..., J, Nk...)
Indices to take along each 1d slice of `arr`. This must match the
dimension of arr, but dimensions Ni and Nj only need to broadcast
against `arr`.
axis : int
The axis to take 1d slices along. If axis is None, the input array is
treated as if it had first been flattened to 1d, for consistency with
`sort` and `argsort`.
Returns
-------
out: ndarray (Ni..., J, Nk...)
The indexed result.
Notes
-----
This is equivalent to (but faster than) the following use of `ndindex` and
`s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices::
Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
J = indices.shape[axis] # Need not equal M
out = np.empty(Ni + (J,) + Nk)
for ii in ndindex(Ni):
for kk in ndindex(Nk):
a_1d = a [ii + s_[:,] + kk]
indices_1d = indices[ii + s_[:,] + kk]
out_1d = out [ii + s_[:,] + kk]
for j in range(J):
out_1d[j] = a_1d[indices_1d[j]]
Equivalently, eliminating the inner loop, the last two lines would be::
out_1d[:] = a_1d[indices_1d]
See Also
--------
take : Take along an axis, using the same indices for every 1d slice
put_along_axis :
Put values into the destination array by matching 1d index and data slices
Examples
--------
>>> import numpy as np
For this sample array
>>> a = np.array([[10, 30, 20], [60, 40, 50]])
We can sort either by using sort directly, or argsort and this function
>>> np.sort(a, axis=1)
array([[10, 20, 30],
[40, 50, 60]])
>>> ai = np.argsort(a, axis=1)
>>> ai
array([[0, 2, 1],
[1, 2, 0]])
>>> np.take_along_axis(a, ai, axis=1)
array([[10, 20, 30],
[40, 50, 60]])
The same works for max and min, if you maintain the trivial dimension
with ``keepdims``:
>>> np.max(a, axis=1, keepdims=True)
array([[30],
[60]])
>>> ai = np.argmax(a, axis=1, keepdims=True)
>>> ai
array([[1],
[0]])
>>> np.take_along_axis(a, ai, axis=1)
array([[30],
[60]])
If we want to get the max and min at the same time, we can stack the
indices first
>>> ai_min = np.argmin(a, axis=1, keepdims=True)
>>> ai_max = np.argmax(a, axis=1, keepdims=True)
>>> ai = np.concatenate([ai_min, ai_max], axis=1)
>>> ai
array([[0, 1],
[1, 0]])
>>> np.take_along_axis(a, ai, axis=1)
array([[10, 30],
[40, 60]])
numpy.tan
Python Library Documentation: ufunc
tan = <ufunc 'tan'>
tan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute tangent element-wise.
Equivalent to ``np.sin(x)/np.cos(x)`` element-wise.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding tangent values.
This is a scalar if `x` is a scalar.
Notes
-----
If `out` is provided, the function writes the result into it,
and returns a reference to `out`. (See Examples)
References
----------
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.
New York, NY: Dover, 1972.
Examples
--------
>>> import numpy as np
>>> from math import pi
>>> np.tan(np.array([-pi,pi/2,pi]))
array([ 1.22460635e-16, 1.63317787e+16, -1.22460635e-16])
>>>
>>> # Example of providing the optional output parameter illustrating
>>> # that what is returned is a reference to said parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.cos([0.1], out1)
>>> out2 is out1
True
>>>
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.cos(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
numpy.tanh
Python Library Documentation: ufunc
tanh = <ufunc 'tanh'>
tanh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Compute hyperbolic tangent element-wise.
Equivalent to ``np.sinh(x)/np.cosh(x)`` or ``-1j * np.tan(1j*x)``.
Parameters
----------
x : array_like
Input array.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The corresponding hyperbolic tangent values.
This is a scalar if `x` is a scalar.
Notes
-----
If `out` is provided, the function writes the result into it,
and returns a reference to `out`. (See Examples)
References
----------
.. [1] M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions.
New York, NY: Dover, 1972, pg. 83.
https://personal.math.ubc.ca/~cbm/aands/page_83.htm
.. [2] Wikipedia, "Hyperbolic function",
https://en.wikipedia.org/wiki/Hyperbolic_function
Examples
--------
>>> import numpy as np
>>> np.tanh((0, np.pi*1j, np.pi*1j/2))
array([ 0. +0.00000000e+00j, 0. -1.22460635e-16j, 0. +1.63317787e+16j])
>>> # Example of providing the optional output parameter illustrating
>>> # that what is returned is a reference to said parameter
>>> out1 = np.array([0], dtype='d')
>>> out2 = np.tanh([0.1], out1)
>>> out2 is out1
True
>>> # Example of ValueError due to provision of shape mis-matched `out`
>>> np.tanh(np.zeros((3,3)),np.zeros((2,2)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
numpy.tensordot
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
tensordot(a, b, axes=2)
Compute tensor dot product along specified axes.
Given two tensors, `a` and `b`, and an array_like object containing
two array_like objects, ``(a_axes, b_axes)``, sum the products of
`a`'s and `b`'s elements (components) over the axes specified by
``a_axes`` and ``b_axes``. The third argument can be a single non-negative
integer_like scalar, ``N``; if it is such, then the last ``N`` dimensions
of `a` and the first ``N`` dimensions of `b` are summed over.
Parameters
----------
a, b : array_like
Tensors to "dot".
axes : int or (2,) array_like
* integer_like
If an int N, sum over the last N axes of `a` and the first N axes
of `b` in order. The sizes of the corresponding axes must match.
* (2,) array_like
Or, a list of axes to be summed over, first sequence applying to `a`,
second to `b`. Both elements array_like must be of the same length.
Returns
-------
output : ndarray
The tensor dot product of the input.
See Also
--------
dot, einsum
Notes
-----
Three common use cases are:
* ``axes = 0`` : tensor product :math:`a\otimes b`
* ``axes = 1`` : tensor dot product :math:`a\cdot b`
* ``axes = 2`` : (default) tensor double contraction :math:`a:b`
When `axes` is a positive integer ``N``, the operation starts with
axis ``-N`` of `a` and axis ``0`` of `b`, and it continues through
axis ``-1`` of `a` and axis ``N-1`` of `b` (inclusive).
When there is more than one axis to sum over - and they are not the last
(first) axes of `a` (`b`) - the argument `axes` should consist of
two sequences of the same length, with the first axis to sum over given
first in both sequences, the second axis second, and so forth.
The shape of the result consists of the non-contracted axes of the
first tensor, followed by the non-contracted axes of the second.
Examples
--------
A "traditional" example:
>>> import numpy as np
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
>>> c.shape
(5, 2)
>>> c
array([[4400., 4730.],
[4532., 4874.],
[4664., 5018.],
[4796., 5162.],
[4928., 5306.]])
>>> # A slower but equivalent way of computing the same...
>>> d = np.zeros((5,2))
>>> for i in range(5):
... for j in range(2):
... for k in range(3):
... for n in range(4):
... d[i,j] += a[k,n,i] * b[n,k,j]
>>> c == d
array([[ True, True],
[ True, True],
[ True, True],
[ True, True],
[ True, True]])
An extended example taking advantage of the overloading of + and \*:
>>> a = np.array(range(1, 9))
>>> a.shape = (2, 2, 2)
>>> A = np.array(('a', 'b', 'c', 'd'), dtype=object)
>>> A.shape = (2, 2)
>>> a; A
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
array([['a', 'b'],
['c', 'd']], dtype=object)
>>> np.tensordot(a, A) # third argument default is 2 for double-contraction
array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object)
>>> np.tensordot(a, A, 1)
array([[['acc', 'bdd'],
['aaacccc', 'bbbdddd']],
[['aaaaacccccc', 'bbbbbdddddd'],
['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object)
>>> np.tensordot(a, A, 0) # tensor product (result too long to incl.)
array([[[[['a', 'b'],
['c', 'd']],
...
>>> np.tensordot(a, A, (0, 1))
array([[['abbbbb', 'cddddd'],
['aabbbbbb', 'ccdddddd']],
[['aaabbbbbbb', 'cccddddddd'],
['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object)
>>> np.tensordot(a, A, (2, 1))
array([[['abb', 'cdd'],
['aaabbbb', 'cccdddd']],
[['aaaaabbbbbb', 'cccccdddddd'],
['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object)
>>> np.tensordot(a, A, ((0, 1), (0, 1)))
array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object)
>>> np.tensordot(a, A, ((2, 1), (1, 0)))
array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
numpy.test
Python Library Documentation: PytestTester in module numpy._pytesttester object
class PytestTester(builtins.object)
| PytestTester(module_name)
|
| Pytest test runner.
|
| A test function is typically added to a package's __init__.py like so::
|
| from numpy._pytesttester import PytestTester
| test = PytestTester(__name__).test
| del PytestTester
|
| Calling this test function finds and runs all tests associated with the
| module and all its sub-modules.
|
| Attributes
| ----------
| module_name : str
| Full path to the package to test.
|
| Parameters
| ----------
| module_name : module name
| The name of the module to test.
|
| Notes
| -----
| Unlike the previous ``nose``-based implementation, this class is not
| publicly exposed as it performs some ``numpy``-specific warning
| suppression.
|
| Methods defined here:
|
| __call__(self, label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False, durations=-1, tests=None)
| Run tests for module using pytest.
|
| Parameters
| ----------
| label : {'fast', 'full'}, optional
| Identifies the tests to run. When set to 'fast', tests decorated
| with `pytest.mark.slow` are skipped, when 'full', the slow marker
| is ignored.
| verbose : int, optional
| Verbosity value for test outputs, in the range 1-3. Default is 1.
| extra_argv : list, optional
| List with any extra arguments to pass to pytests.
| doctests : bool, optional
| .. note:: Not supported
| coverage : bool, optional
| If True, report coverage of NumPy code. Default is False.
| Requires installation of (pip) pytest-cov.
| durations : int, optional
| If < 0, do nothing, If 0, report time of all tests, if > 0,
| report the time of the slowest `timer` tests. Default is -1.
| tests : test or list of tests
| Tests to be executed with pytest '--pyargs'
|
| Returns
| -------
| result : bool
| Return True on success, false otherwise.
|
| Notes
| -----
| Each NumPy module exposes `test` in its namespace to run all tests for
| it. For example, to run all tests for numpy.lib:
|
| >>> np.lib.test() #doctest: +SKIP
|
| Examples
| --------
| >>> result = np.lib.test() #doctest: +SKIP
| ...
| 1023 passed, 2 skipped, 6 deselected, 1 xfailed in 10.39 seconds
| >>> result
| True
|
| __init__(self, module_name)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
numpy.testing
Python Library Documentation: package numpy.testing in numpy
NAME
numpy.testing - Common test support for all numpy test scripts.
DESCRIPTION
This single module should provide all the common functionality for numpy tests
in a single location, so that test scripts can just import it and work right
away.
PACKAGE CONTENTS
_private (package)
overrides
print_coercion_tables
tests (package)
SUBMODULES
extbuild
CLASSES
builtins.Exception(builtins.BaseException)
numpy.testing._private.utils.IgnoreException
numpy.testing._private.utils.KnownFailureException
unittest.case.SkipTest
builtins.object
numpy.testing._private.utils.suppress_warnings
unittest.case.TestCase
warnings.catch_warnings(builtins.object)
numpy.testing._private.utils.clear_and_catch_warnings
class IgnoreException(builtins.Exception)
| Ignoring this exception due to disabled feature
|
| Method resolution order:
| IgnoreException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.Exception:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class KnownFailureException(builtins.Exception)
| Raise this exception to mark a test as a known failing test.
|
| Method resolution order:
| KnownFailureException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.Exception:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class SkipTest(builtins.Exception)
| Raise this exception in a test to skip it.
|
| Usually you can use TestCase.skipTest() or one of the skipping decorators
| instead of raising this directly.
|
| Method resolution order:
| SkipTest
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.Exception:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class TestCase(builtins.object)
| TestCase(methodName='runTest')
|
| A class whose instances are single test cases.
|
| By default, the test code itself should be placed in a method named
| 'runTest'.
|
| If the fixture may be used for many test cases, create as
| many test methods as are needed. When instantiating such a TestCase
| subclass, specify in the constructor arguments the name of the test method
| that the instance is to execute.
|
| Test authors should subclass TestCase for their own tests. Construction
| and deconstruction of the test's environment ('fixture') can be
| implemented by overriding the 'setUp' and 'tearDown' methods respectively.
|
| If it is necessary to override the __init__ method, the base class
| __init__ method must always be called. It is important that subclasses
| should not change the signature of their __init__ method, since instances
| of the classes are instantiated automatically by parts of the framework
| in order to be run.
|
| When subclassing TestCase, you can set these attributes:
| * failureException: determines which exception will be raised when
| the instance's assertion methods fail; test methods raising this
| exception will be deemed to have 'failed' rather than 'errored'.
| * longMessage: determines whether long messages (including repr of
| objects used in assert methods) will be printed on failure in *addition*
| to any explicit message passed.
| * maxDiff: sets the maximum length of a diff in failure messages
| by assert methods using difflib. It is looked up as an instance
| attribute so can be configured by individual tests if required.
|
| Methods defined here:
|
| __call__(self, *args, **kwds)
| Call self as a function.
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, methodName='runTest')
| Create an instance of the class that will use the named test
| method when executed. Raises a ValueError if the instance does
| not have a method with the specified name.
|
| __repr__(self)
| Return repr(self).
|
| __str__(self)
| Return str(self).
|
| addCleanup(self, function, /, *args, **kwargs)
| Add a function, with arguments, to be called when the test is
| completed. Functions added are called on a LIFO basis and are
| called after tearDown on test failure or success.
|
| Cleanup items are called even if setUp fails (unlike tearDown).
|
| addTypeEqualityFunc(self, typeobj, function)
| Add a type specific assertEqual style function to compare a type.
|
| This method is for use by TestCase subclasses that need to register
| their own type equality functions to provide nicer error messages.
|
| Args:
| typeobj: The data type to call this function on when both values
| are of the same type in assertEqual().
| function: The callable taking two arguments and an optional
| msg= argument that raises self.failureException with a
| useful error message when the two arguments are not equal.
|
| assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)
| Fail if the two objects are unequal as determined by their
| difference rounded to the given number of decimal places
| (default 7) and comparing to zero, or by comparing that the
| difference between the two objects is more than the given
| delta.
|
| Note that decimal places (from zero) are usually not the same
| as significant digits (measured from the most significant digit).
|
| If the two objects compare equal then they will automatically
| compare almost equal.
|
| assertCountEqual(self, first, second, msg=None)
| Asserts that two iterables have the same elements, the same number of
| times, without regard to order.
|
| self.assertEqual(Counter(list(first)),
| Counter(list(second)))
|
| Example:
| - [0, 1, 1] and [1, 0, 1] compare equal.
| - [0, 0, 1] and [0, 1] compare unequal.
|
| assertDictEqual(self, d1, d2, msg=None)
|
| assertEqual(self, first, second, msg=None)
| Fail if the two objects are unequal as determined by the '=='
| operator.
|
| assertFalse(self, expr, msg=None)
| Check that the expression is false.
|
| assertGreater(self, a, b, msg=None)
| Just like self.assertTrue(a > b), but with a nicer default message.
|
| assertGreaterEqual(self, a, b, msg=None)
| Just like self.assertTrue(a >= b), but with a nicer default message.
|
| assertIn(self, member, container, msg=None)
| Just like self.assertTrue(a in b), but with a nicer default message.
|
| assertIs(self, expr1, expr2, msg=None)
| Just like self.assertTrue(a is b), but with a nicer default message.
|
| assertIsInstance(self, obj, cls, msg=None)
| Same as self.assertTrue(isinstance(obj, cls)), with a nicer
| default message.
|
| assertIsNone(self, obj, msg=None)
| Same as self.assertTrue(obj is None), with a nicer default message.
|
| assertIsNot(self, expr1, expr2, msg=None)
| Just like self.assertTrue(a is not b), but with a nicer default message.
|
| assertIsNotNone(self, obj, msg=None)
| Included for symmetry with assertIsNone.
|
| assertLess(self, a, b, msg=None)
| Just like self.assertTrue(a < b), but with a nicer default message.
|
| assertLessEqual(self, a, b, msg=None)
| Just like self.assertTrue(a <= b), but with a nicer default message.
|
| assertListEqual(self, list1, list2, msg=None)
| A list-specific equality assertion.
|
| Args:
| list1: The first list to compare.
| list2: The second list to compare.
| msg: Optional message to use on failure instead of a list of
| differences.
|
| assertLogs(self, logger=None, level=None)
| Fail unless a log message of level *level* or higher is emitted
| on *logger_name* or its children. If omitted, *level* defaults to
| INFO and *logger* defaults to the root logger.
|
| This method must be used as a context manager, and will yield
| a recording object with two attributes: `output` and `records`.
| At the end of the context manager, the `output` attribute will
| be a list of the matching formatted log messages and the
| `records` attribute will be a list of the corresponding LogRecord
| objects.
|
| Example::
|
| with self.assertLogs('foo', level='INFO') as cm:
| logging.getLogger('foo').info('first message')
| logging.getLogger('foo.bar').error('second message')
| self.assertEqual(cm.output, ['INFO:foo:first message',
| 'ERROR:foo.bar:second message'])
|
| assertMultiLineEqual(self, first, second, msg=None)
| Assert that two multi-line strings are equal.
|
| assertNoLogs(self, logger=None, level=None)
| Fail unless no log messages of level *level* or higher are emitted
| on *logger_name* or its children.
|
| This method must be used as a context manager.
|
| assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)
| Fail if the two objects are equal as determined by their
| difference rounded to the given number of decimal places
| (default 7) and comparing to zero, or by comparing that the
| difference between the two objects is less than the given delta.
|
| Note that decimal places (from zero) are usually not the same
| as significant digits (measured from the most significant digit).
|
| Objects that are equal automatically fail.
|
| assertNotEqual(self, first, second, msg=None)
| Fail if the two objects are equal as determined by the '!='
| operator.
|
| assertNotIn(self, member, container, msg=None)
| Just like self.assertTrue(a not in b), but with a nicer default message.
|
| assertNotIsInstance(self, obj, cls, msg=None)
| Included for symmetry with assertIsInstance.
|
| assertNotRegex(self, text, unexpected_regex, msg=None)
| Fail the test if the text matches the regular expression.
|
| assertRaises(self, expected_exception, *args, **kwargs)
| Fail unless an exception of class expected_exception is raised
| by the callable when invoked with specified positional and
| keyword arguments. If a different type of exception is
| raised, it will not be caught, and the test case will be
| deemed to have suffered an error, exactly as for an
| unexpected exception.
|
| If called with the callable and arguments omitted, will return a
| context object used like this::
|
| with self.assertRaises(SomeException):
| do_something()
|
| An optional keyword argument 'msg' can be provided when assertRaises
| is used as a context object.
|
| The context manager keeps a reference to the exception as
| the 'exception' attribute. This allows you to inspect the
| exception after the assertion::
|
| with self.assertRaises(SomeException) as cm:
| do_something()
| the_exception = cm.exception
| self.assertEqual(the_exception.error_code, 3)
|
| assertRaisesRegex(self, expected_exception, expected_regex, *args, **kwargs)
| Asserts that the message in a raised exception matches a regex.
|
| Args:
| expected_exception: Exception class expected to be raised.
| expected_regex: Regex (re.Pattern object or string) expected
| to be found in error message.
| args: Function to be called and extra positional args.
| kwargs: Extra kwargs.
| msg: Optional message used in case of failure. Can only be used
| when assertRaisesRegex is used as a context manager.
|
| assertRegex(self, text, expected_regex, msg=None)
| Fail the test unless the text matches the regular expression.
|
| assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None)
| An equality assertion for ordered sequences (like lists and tuples).
|
| For the purposes of this function, a valid ordered sequence type is one
| which can be indexed, has a length, and has an equality operator.
|
| Args:
| seq1: The first sequence to compare.
| seq2: The second sequence to compare.
| seq_type: The expected datatype of the sequences, or None if no
| datatype should be enforced.
| msg: Optional message to use on failure instead of a list of
| differences.
|
| assertSetEqual(self, set1, set2, msg=None)
| A set-specific equality assertion.
|
| Args:
| set1: The first set to compare.
| set2: The second set to compare.
| msg: Optional message to use on failure instead of a list of
| differences.
|
| assertSetEqual uses ducktyping to support different types of sets, and
| is optimized for sets specifically (parameters must support a
| difference method).
|
| assertTrue(self, expr, msg=None)
| Check that the expression is true.
|
| assertTupleEqual(self, tuple1, tuple2, msg=None)
| A tuple-specific equality assertion.
|
| Args:
| tuple1: The first tuple to compare.
| tuple2: The second tuple to compare.
| msg: Optional message to use on failure instead of a list of
| differences.
|
| assertWarns(self, expected_warning, *args, **kwargs)
| Fail unless a warning of class warnClass is triggered
| by the callable when invoked with specified positional and
| keyword arguments. If a different type of warning is
| triggered, it will not be handled: depending on the other
| warning filtering rules in effect, it might be silenced, printed
| out, or raised as an exception.
|
| If called with the callable and arguments omitted, will return a
| context object used like this::
|
| with self.assertWarns(SomeWarning):
| do_something()
|
| An optional keyword argument 'msg' can be provided when assertWarns
| is used as a context object.
|
| The context manager keeps a reference to the first matching
| warning as the 'warning' attribute; similarly, the 'filename'
| and 'lineno' attributes give you information about the line
| of Python code from which the warning was triggered.
| This allows you to inspect the warning after the assertion::
|
| with self.assertWarns(SomeWarning) as cm:
| do_something()
| the_warning = cm.warning
| self.assertEqual(the_warning.some_attribute, 147)
|
| assertWarnsRegex(self, expected_warning, expected_regex, *args, **kwargs)
| Asserts that the message in a triggered warning matches a regexp.
| Basic functioning is similar to assertWarns() with the addition
| that only warnings whose messages also match the regular expression
| are considered successful matches.
|
| Args:
| expected_warning: Warning class expected to be triggered.
| expected_regex: Regex (re.Pattern object or string) expected
| to be found in error message.
| args: Function to be called and extra positional args.
| kwargs: Extra kwargs.
| msg: Optional message used in case of failure. Can only be used
| when assertWarnsRegex is used as a context manager.
|
| countTestCases(self)
|
| debug(self)
| Run the test without collecting errors in a TestResult
|
| defaultTestResult(self)
|
| doCleanups(self)
| Execute all cleanup functions. Normally called for you after
| tearDown.
|
| enterContext(self, cm)
| Enters the supplied context manager.
|
| If successful, also adds its __exit__ method as a cleanup
| function and returns the result of the __enter__ method.
|
| fail(self, msg=None)
| Fail immediately, with the given message.
|
| id(self)
|
| run(self, result=None)
|
| setUp(self)
| Hook method for setting up the test fixture before exercising it.
|
| shortDescription(self)
| Returns a one-line description of the test, or None if no
| description has been provided.
|
| The default implementation of this method returns the first line of
| the specified test method's docstring.
|
| skipTest(self, reason)
| Skip this test.
|
| subTest(self, msg=<object object at 0x000002E7A347B9D0>, **params)
| Return a context manager that will return the enclosed block
| of code in a subtest identified by the optional message and
| keyword parameters. A failure in the subtest marks the test
| case as failed but resumes execution at the end of the enclosed
| block, allowing further test code to be executed.
|
| tearDown(self)
| Hook method for deconstructing the test fixture after testing it.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __init_subclass__(*args, **kwargs)
| This method is called when a class is subclassed.
|
| The default implementation does nothing. It may be
| overridden to extend subclasses.
|
| addClassCleanup(function, /, *args, **kwargs)
| Same as addCleanup, except the cleanup items are called even if
| setUpClass fails (unlike tearDownClass).
|
| doClassCleanups()
| Execute all class cleanup functions. Normally called for you after
| tearDownClass.
|
| enterClassContext(cm)
| Same as enterContext, but class-wide.
|
| setUpClass()
| Hook method for setting up class fixture before running tests in the class.
|
| tearDownClass()
| Hook method for deconstructing the class fixture after running all tests in the class.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| failureException = <class 'AssertionError'>
| Assertion failed.
|
|
| longMessage = True
|
| maxDiff = 640
class clear_and_catch_warnings(warnings.catch_warnings)
| clear_and_catch_warnings(record=False, modules=())
|
| Context manager that resets warning registry for catching warnings
|
| Warnings can be slippery, because, whenever a warning is triggered, Python
| adds a ``__warningregistry__`` member to the *calling* module. This makes
| it impossible to retrigger the warning in this module, whatever you put in
| the warnings filters. This context manager accepts a sequence of `modules`
| as a keyword argument to its constructor and:
|
| * stores and removes any ``__warningregistry__`` entries in given `modules`
| on entry;
| * resets ``__warningregistry__`` to its previous state on exit.
|
| This makes it possible to trigger any warning afresh inside the context
| manager without disturbing the state of warnings outside.
|
| For compatibility with Python 3.0, please consider all arguments to be
| keyword-only.
|
| Parameters
| ----------
| record : bool, optional
| Specifies whether warnings should be captured by a custom
| implementation of ``warnings.showwarning()`` and be appended to a list
| returned by the context manager. Otherwise None is returned by the
| context manager. The objects appended to the list are arguments whose
| attributes mirror the arguments to ``showwarning()``.
| modules : sequence, optional
| Sequence of modules for which to reset warnings registry on entry and
| restore on exit. To work correctly, all 'ignore' filters should
| filter by one of these modules.
|
| Examples
| --------
| >>> import warnings
| >>> with np.testing.clear_and_catch_warnings(
| ... modules=[np._core.fromnumeric]):
| ... warnings.simplefilter('always')
| ... warnings.filterwarnings('ignore', module='np._core.fromnumeric')
| ... # do something that raises a warning but ignore those in
| ... # np._core.fromnumeric
|
| Method resolution order:
| clear_and_catch_warnings
| warnings.catch_warnings
| builtins.object
|
| Methods defined here:
|
| __enter__(self)
|
| __exit__(self, *exc_info)
|
| __init__(self, record=False, modules=())
| Specify whether to record warnings and if an alternative module
| should be used other than sys.modules['warnings'].
|
| For compatibility with Python 3.0, please consider all arguments to be
| keyword-only.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| class_modules = ()
|
| ----------------------------------------------------------------------
| Methods inherited from warnings.catch_warnings:
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from warnings.catch_warnings:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class suppress_warnings(builtins.object)
| suppress_warnings(forwarding_rule='always')
|
| Context manager and decorator doing much the same as
| ``warnings.catch_warnings``.
|
| However, it also provides a filter mechanism to work around
| https://bugs.python.org/issue4180.
|
| This bug causes Python before 3.4 to not reliably show warnings again
| after they have been ignored once (even within catch_warnings). It
| means that no "ignore" filter can be used easily, since following
| tests might need to see the warning. Additionally it allows easier
| specificity for testing warnings and can be nested.
|
| Parameters
| ----------
| forwarding_rule : str, optional
| One of "always", "once", "module", or "location". Analogous to
| the usual warnings module filter mode, it is useful to reduce
| noise mostly on the outmost level. Unsuppressed and unrecorded
| warnings will be forwarded based on this rule. Defaults to "always".
| "location" is equivalent to the warnings "default", match by exact
| location the warning warning originated from.
|
| Notes
| -----
| Filters added inside the context manager will be discarded again
| when leaving it. Upon entering all filters defined outside a
| context will be applied automatically.
|
| When a recording filter is added, matching warnings are stored in the
| ``log`` attribute as well as in the list returned by ``record``.
|
| If filters are added and the ``module`` keyword is given, the
| warning registry of this module will additionally be cleared when
| applying it, entering the context, or exiting it. This could cause
| warnings to appear a second time after leaving the context if they
| were configured to be printed once (default) and were already
| printed before the context was entered.
|
| Nesting this context manager will work as expected when the
| forwarding rule is "always" (default). Unfiltered and unrecorded
| warnings will be passed out and be matched by the outer level.
| On the outmost level they will be printed (or caught by another
| warnings context). The forwarding rule argument can modify this
| behaviour.
|
| Like ``catch_warnings`` this context manager is not threadsafe.
|
| Examples
| --------
|
| With a context manager::
|
| with np.testing.suppress_warnings() as sup:
| sup.filter(DeprecationWarning, "Some text")
| sup.filter(module=np.ma.core)
| log = sup.record(FutureWarning, "Does this occur?")
| command_giving_warnings()
| # The FutureWarning was given once, the filtered warnings were
| # ignored. All other warnings abide outside settings (may be
| # printed/error)
| assert_(len(log) == 1)
| assert_(len(sup.log) == 1) # also stored in log attribute
|
| Or as a decorator::
|
| sup = np.testing.suppress_warnings()
| sup.filter(module=np.ma.core) # module must match exactly
| @sup
| def some_function():
| # do something which causes a warning in np.ma.core
| pass
|
| Methods defined here:
|
| __call__(self, func)
| Function decorator to apply certain suppressions to a whole
| function.
|
| __enter__(self)
|
| __exit__(self, *exc_info)
|
| __init__(self, forwarding_rule='always')
| Initialize self. See help(type(self)) for accurate signature.
|
| filter(self, category=<class 'Warning'>, message='', module=None)
| Add a new suppressing filter or apply it if the state is entered.
|
| Parameters
| ----------
| category : class, optional
| Warning class to filter
| message : string, optional
| Regular expression matching the warning message.
| module : module, optional
| Module to filter for. Note that the module (and its file)
| must match exactly and cannot be a submodule. This may make
| it unreliable for external modules.
|
| Notes
| -----
| When added within a context, filters are only added inside
| the context and will be forgotten when the context is exited.
|
| record(self, category=<class 'Warning'>, message='', module=None)
| Append a new recording filter or apply it if the state is entered.
|
| All warnings matching will be appended to the ``log`` attribute.
|
| Parameters
| ----------
| category : class, optional
| Warning class to filter
| message : string, optional
| Regular expression matching the warning message.
| module : module, optional
| Module to filter for. Note that the module (and its file)
| must match exactly and cannot be a submodule. This may make
| it unreliable for external modules.
|
| Returns
| -------
| log : list
| A list which will be filled with all matched warnings.
|
| Notes
| -----
| When added within a context, filters are only added inside
| the context and will be forgotten when the context is exited.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
_OLD_PROMOTION lambda (...)
assert_(val, msg='')
Assert that works in release mode.
Accepts callable msg to allow deferring evaluation until failure.
The Python built-in ``assert`` does not work when executing code in
optimized mode (the ``-O`` flag) - no byte-code is generated for it.
For documentation on usage, refer to the Python documentation.
assert_allclose(actual, desired, rtol=1e-07, atol=0, equal_nan=True, err_msg='', verbose=True, *, strict=False)
Raises an AssertionError if two objects are not equal up to desired
tolerance.
Given two array_like objects, check that their shapes and all elements
are equal (but see the Notes for the special handling of a scalar). An
exception is raised if the shapes mismatch or any values conflict. In
contrast to the standard usage in numpy, NaNs are compared like numbers,
no assertion is raised if both objects have NaNs in the same positions.
The test is equivalent to ``allclose(actual, desired, rtol, atol)`` (note
that ``allclose`` has different default values). It compares the difference
between `actual` and `desired` to ``atol + rtol * abs(desired)``.
.. versionadded:: 1.5.0
Parameters
----------
actual : array_like
Array obtained.
desired : array_like
Array desired.
rtol : float, optional
Relative tolerance.
atol : float, optional
Absolute tolerance.
equal_nan : bool, optional.
If True, NaNs will compare equal.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
strict : bool, optional
If True, raise an ``AssertionError`` when either the shape or the data
type of the arguments does not match. The special handling of scalars
mentioned in the Notes section is disabled.
.. versionadded:: 2.0.0
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_array_almost_equal_nulp, assert_array_max_ulp
Notes
-----
When one of `actual` and `desired` is a scalar and the other is
array_like, the function performs the comparison as if the scalar were
broadcasted to the shape of the array.
This behaviour can be disabled with the `strict` parameter.
Examples
--------
>>> x = [1e-5, 1e-3, 1e-1]
>>> y = np.arccos(np.cos(x))
>>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
As mentioned in the Notes section, `assert_allclose` has special
handling for scalars. Here, the test checks that the value of `numpy.sin`
is nearly zero at integer multiples of π.
>>> x = np.arange(3) * np.pi
>>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15)
Use `strict` to raise an ``AssertionError`` when comparing an array
with one or more dimensions against a scalar.
>>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15, strict=True)
Traceback (most recent call last):
...
AssertionError:
Not equal to tolerance rtol=1e-07, atol=1e-15
<BLANKLINE>
(shapes (3,), () mismatch)
ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16])
DESIRED: array(0)
The `strict` parameter also ensures that the array data types match:
>>> y = np.zeros(3, dtype=np.float32)
>>> np.testing.assert_allclose(np.sin(x), y, atol=1e-15, strict=True)
Traceback (most recent call last):
...
AssertionError:
Not equal to tolerance rtol=1e-07, atol=1e-15
<BLANKLINE>
(dtypes float64, float32 mismatch)
ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16])
DESIRED: array([0., 0., 0.], dtype=float32)
assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True)
Raises an AssertionError if two items are not equal up to desired
precision.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
The test verifies that the elements of `actual` and `desired` satisfy::
abs(desired-actual) < float64(1.5 * 10**(-decimal))
That is a looser test than originally documented, but agrees with what the
actual implementation in `assert_array_almost_equal` did up to rounding
vagaries. An exception is raised at conflicting values. For ndarrays this
delegates to assert_array_almost_equal
Parameters
----------
actual : array_like
The object to check.
desired : array_like
The expected object.
decimal : int, optional
Desired precision, default is 7.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Examples
--------
>>> from numpy.testing import assert_almost_equal
>>> assert_almost_equal(2.3333333333333, 2.33333334)
>>> assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
Traceback (most recent call last):
...
AssertionError:
Arrays are not almost equal to 10 decimals
ACTUAL: 2.3333333333333
DESIRED: 2.33333334
>>> assert_almost_equal(np.array([1.0,2.3333333333333]),
... np.array([1.0,2.33333334]), decimal=9)
Traceback (most recent call last):
...
AssertionError:
Arrays are not almost equal to 9 decimals
<BLANKLINE>
Mismatched elements: 1 / 2 (50%)
Max absolute difference among violations: 6.66669964e-09
Max relative difference among violations: 2.85715698e-09
ACTUAL: array([1. , 2.333333333])
DESIRED: array([1. , 2.33333334])
assert_approx_equal(actual, desired, significant=7, err_msg='', verbose=True)
Raises an AssertionError if two items are not equal up to significant
digits.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
Given two numbers, check that they are approximately equal.
Approximately equal is defined as the number of significant digits
that agree.
Parameters
----------
actual : scalar
The object to check.
desired : scalar
The expected object.
significant : int, optional
Desired precision, default is 7.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Examples
--------
>>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,
... significant=8)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,
... significant=8)
Traceback (most recent call last):
...
AssertionError:
Items are not equal to 8 significant digits:
ACTUAL: 1.234567e-21
DESIRED: 1.2345672e-21
the evaluated condition that raises the exception is
>>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1)
True
assert_array_almost_equal(actual, desired, decimal=6, err_msg='', verbose=True)
Raises an AssertionError if two objects are not equal up to desired
precision.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
The test verifies identical shapes and that the elements of ``actual`` and
``desired`` satisfy::
abs(desired-actual) < 1.5 * 10**(-decimal)
That is a looser test than originally documented, but agrees with what the
actual implementation did up to rounding vagaries. An exception is raised
at shape mismatch or conflicting values. In contrast to the standard usage
in numpy, NaNs are compared like numbers, no assertion is raised if both
objects have NaNs in the same positions.
Parameters
----------
actual : array_like
The actual object to check.
desired : array_like
The desired, expected object.
decimal : int, optional
Desired precision, default is 6.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Examples
--------
the first assert does not raise an exception
>>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
... [1.0,2.333,np.nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
... [1.0,2.33339,np.nan], decimal=5)
Traceback (most recent call last):
...
AssertionError:
Arrays are not almost equal to 5 decimals
<BLANKLINE>
Mismatched elements: 1 / 3 (33.3%)
Max absolute difference among violations: 6.e-05
Max relative difference among violations: 2.57136612e-05
ACTUAL: array([1. , 2.33333, nan])
DESIRED: array([1. , 2.33339, nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
... [1.0,2.33333, 5], decimal=5)
Traceback (most recent call last):
...
AssertionError:
Arrays are not almost equal to 5 decimals
<BLANKLINE>
nan location mismatch:
ACTUAL: array([1. , 2.33333, nan])
DESIRED: array([1. , 2.33333, 5. ])
assert_array_almost_equal_nulp(x, y, nulp=1)
Compare two arrays relatively to their spacing.
This is a relatively robust method to compare two arrays whose amplitude
is variable.
Parameters
----------
x, y : array_like
Input arrays.
nulp : int, optional
The maximum number of unit in the last place for tolerance (see Notes).
Default is 1.
Returns
-------
None
Raises
------
AssertionError
If the spacing between `x` and `y` for one or more elements is larger
than `nulp`.
See Also
--------
assert_array_max_ulp : Check that all items of arrays differ in at most
N Units in the Last Place.
spacing : Return the distance between x and the nearest adjacent number.
Notes
-----
An assertion is raised if the following condition is not met::
abs(x - y) <= nulp * spacing(maximum(abs(x), abs(y)))
Examples
--------
>>> x = np.array([1., 1e-10, 1e-20])
>>> eps = np.finfo(x.dtype).eps
>>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)
>>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
Traceback (most recent call last):
...
AssertionError: Arrays are not equal to 1 ULP (max is 2)
assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='', precision=6, equal_nan=True, equal_inf=True, *, strict=False, names=('ACTUAL', 'DESIRED'))
assert_array_equal(actual, desired, err_msg='', verbose=True, *, strict=False)
Raises an AssertionError if two array_like objects are not equal.
Given two array_like objects, check that the shape is equal and all
elements of these objects are equal (but see the Notes for the special
handling of a scalar). An exception is raised at shape mismatch or
conflicting values. In contrast to the standard usage in numpy, NaNs
are compared like numbers, no assertion is raised if both objects have
NaNs in the same positions.
The usual caution for verifying equality with floating point numbers is
advised.
.. note:: When either `actual` or `desired` is already an instance of
`numpy.ndarray` and `desired` is not a ``dict``, the behavior of
``assert_equal(actual, desired)`` is identical to the behavior of this
function. Otherwise, this function performs `np.asanyarray` on the
inputs before comparison, whereas `assert_equal` defines special
comparison rules for common Python types. For example, only
`assert_equal` can be used to compare nested Python lists. In new code,
consider using only `assert_equal`, explicitly converting either
`actual` or `desired` to arrays if the behavior of `assert_array_equal`
is desired.
Parameters
----------
actual : array_like
The actual object to check.
desired : array_like
The desired, expected object.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
strict : bool, optional
If True, raise an AssertionError when either the shape or the data
type of the array_like objects does not match. The special
handling for scalars mentioned in the Notes section is disabled.
.. versionadded:: 1.24.0
Raises
------
AssertionError
If actual and desired objects are not equal.
See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal
Notes
-----
When one of `actual` and `desired` is a scalar and the other is array_like,
the function checks that each element of the array_like object is equal to
the scalar. This behaviour can be disabled with the `strict` parameter.
Examples
--------
The first assert does not raise an exception:
>>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
... [np.exp(0),2.33333, np.nan])
Assert fails with numerical imprecision with floats:
>>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
... [1, np.sqrt(np.pi)**2, np.nan])
Traceback (most recent call last):
...
AssertionError:
Arrays are not equal
<BLANKLINE>
Mismatched elements: 1 / 3 (33.3%)
Max absolute difference among violations: 4.4408921e-16
Max relative difference among violations: 1.41357986e-16
ACTUAL: array([1. , 3.141593, nan])
DESIRED: array([1. , 3.141593, nan])
Use `assert_allclose` or one of the nulp (number of floating point values)
functions for these cases instead:
>>> np.testing.assert_allclose([1.0,np.pi,np.nan],
... [1, np.sqrt(np.pi)**2, np.nan],
... rtol=1e-10, atol=0)
As mentioned in the Notes section, `assert_array_equal` has special
handling for scalars. Here the test checks that each value in `x` is 3:
>>> x = np.full((2, 5), fill_value=3)
>>> np.testing.assert_array_equal(x, 3)
Use `strict` to raise an AssertionError when comparing a scalar with an
array:
>>> np.testing.assert_array_equal(x, 3, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not equal
<BLANKLINE>
(shapes (2, 5), () mismatch)
ACTUAL: array([[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3]])
DESIRED: array(3)
The `strict` parameter also ensures that the array data types match:
>>> x = np.array([2, 2, 2])
>>> y = np.array([2., 2., 2.], dtype=np.float32)
>>> np.testing.assert_array_equal(x, y, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not equal
<BLANKLINE>
(dtypes int64, float32 mismatch)
ACTUAL: array([2, 2, 2])
DESIRED: array([2., 2., 2.], dtype=float32)
assert_array_less(x, y, err_msg='', verbose=True, *, strict=False)
Raises an AssertionError if two array_like objects are not ordered by less
than.
Given two array_like objects `x` and `y`, check that the shape is equal and
all elements of `x` are strictly less than the corresponding elements of
`y` (but see the Notes for the special handling of a scalar). An exception
is raised at shape mismatch or values that are not correctly ordered. In
contrast to the standard usage in NumPy, no assertion is raised if both
objects have NaNs in the same positions.
Parameters
----------
x : array_like
The smaller object to check.
y : array_like
The larger object to compare.
err_msg : string
The error message to be printed in case of failure.
verbose : bool
If True, the conflicting values are appended to the error message.
strict : bool, optional
If True, raise an AssertionError when either the shape or the data
type of the array_like objects does not match. The special
handling for scalars mentioned in the Notes section is disabled.
.. versionadded:: 2.0.0
Raises
------
AssertionError
If x is not strictly smaller than y, element-wise.
See Also
--------
assert_array_equal: tests objects for equality
assert_array_almost_equal: test objects for equality up to precision
Notes
-----
When one of `x` and `y` is a scalar and the other is array_like, the
function performs the comparison as though the scalar were broadcasted
to the shape of the array. This behaviour can be disabled with the `strict`
parameter.
Examples
--------
The following assertion passes because each finite element of `x` is
strictly less than the corresponding element of `y`, and the NaNs are in
corresponding locations.
>>> x = [1.0, 1.0, np.nan]
>>> y = [1.1, 2.0, np.nan]
>>> np.testing.assert_array_less(x, y)
The following assertion fails because the zeroth element of `x` is no
longer strictly less than the zeroth element of `y`.
>>> y[0] = 1
>>> np.testing.assert_array_less(x, y)
Traceback (most recent call last):
...
AssertionError:
Arrays are not strictly ordered `x < y`
<BLANKLINE>
Mismatched elements: 1 / 3 (33.3%)
Max absolute difference among violations: 0.
Max relative difference among violations: 0.
x: array([ 1., 1., nan])
y: array([ 1., 2., nan])
Here, `y` is a scalar, so each element of `x` is compared to `y`, and
the assertion passes.
>>> x = [1.0, 4.0]
>>> y = 5.0
>>> np.testing.assert_array_less(x, y)
However, with ``strict=True``, the assertion will fail because the shapes
do not match.
>>> np.testing.assert_array_less(x, y, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not strictly ordered `x < y`
<BLANKLINE>
(shapes (2,), () mismatch)
x: array([1., 4.])
y: array(5.)
With ``strict=True``, the assertion also fails if the dtypes of the two
arrays do not match.
>>> y = [5, 5]
>>> np.testing.assert_array_less(x, y, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not strictly ordered `x < y`
<BLANKLINE>
(dtypes float64, int64 mismatch)
x: array([1., 4.])
y: array([5, 5])
assert_array_max_ulp(a, b, maxulp=1, dtype=None)
Check that all items of arrays differ in at most N Units in the Last Place.
Parameters
----------
a, b : array_like
Input arrays to be compared.
maxulp : int, optional
The maximum number of units in the last place that elements of `a` and
`b` can differ. Default is 1.
dtype : dtype, optional
Data-type to convert `a` and `b` to if given. Default is None.
Returns
-------
ret : ndarray
Array containing number of representable floating point numbers between
items in `a` and `b`.
Raises
------
AssertionError
If one or more elements differ by more than `maxulp`.
Notes
-----
For computing the ULP difference, this API does not differentiate between
various representations of NAN (ULP difference between 0x7fc00000 and 0xffc00000
is zero).
See Also
--------
assert_array_almost_equal_nulp : Compare two arrays relatively to their
spacing.
Examples
--------
>>> a = np.linspace(0., 1., 100)
>>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a)))
assert_equal(actual, desired, err_msg='', verbose=True, *, strict=False)
Raises an AssertionError if two objects are not equal.
Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
check that all elements of these objects are equal. An exception is raised
at the first conflicting values.
This function handles NaN comparisons as if NaN was a "normal" number.
That is, AssertionError is not raised if both objects have NaNs in the same
positions. This is in contrast to the IEEE standard on NaNs, which says
that NaN compared to anything must return False.
Parameters
----------
actual : array_like
The object to check.
desired : array_like
The expected object.
err_msg : str, optional
The error message to be printed in case of failure.
verbose : bool, optional
If True, the conflicting values are appended to the error message.
strict : bool, optional
If True and either of the `actual` and `desired` arguments is an array,
raise an ``AssertionError`` when either the shape or the data type of
the arguments does not match. If neither argument is an array, this
parameter has no effect.
.. versionadded:: 2.0.0
Raises
------
AssertionError
If actual and desired are not equal.
See Also
--------
assert_allclose
assert_array_almost_equal_nulp,
assert_array_max_ulp,
Notes
-----
By default, when one of `actual` and `desired` is a scalar and the other is
an array, the function checks that each element of the array is equal to
the scalar. This behaviour can be disabled by setting ``strict==True``.
Examples
--------
>>> np.testing.assert_equal([4, 5], [4, 6])
Traceback (most recent call last):
...
AssertionError:
Items are not equal:
item=1
ACTUAL: 5
DESIRED: 6
The following comparison does not raise an exception. There are NaNs
in the inputs, but they are in the same positions.
>>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])
As mentioned in the Notes section, `assert_equal` has special
handling for scalars when one of the arguments is an array.
Here, the test checks that each value in `x` is 3:
>>> x = np.full((2, 5), fill_value=3)
>>> np.testing.assert_equal(x, 3)
Use `strict` to raise an AssertionError when comparing a scalar with an
array of a different shape:
>>> np.testing.assert_equal(x, 3, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not equal
<BLANKLINE>
(shapes (2, 5), () mismatch)
ACTUAL: array([[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3]])
DESIRED: array(3)
The `strict` parameter also ensures that the array data types match:
>>> x = np.array([2, 2, 2])
>>> y = np.array([2., 2., 2.], dtype=np.float32)
>>> np.testing.assert_equal(x, y, strict=True)
Traceback (most recent call last):
...
AssertionError:
Arrays are not equal
<BLANKLINE>
(dtypes int64, float32 mismatch)
ACTUAL: array([2, 2, 2])
DESIRED: array([2., 2., 2.], dtype=float32)
assert_no_gc_cycles(*args, **kwargs)
Fail if the given callable produces any reference cycles.
If called with all arguments omitted, may be used as a context manager::
with assert_no_gc_cycles():
do_something()
.. versionadded:: 1.15.0
Parameters
----------
func : callable
The callable to test.
\*args : Arguments
Arguments passed to `func`.
\*\*kwargs : Kwargs
Keyword arguments passed to `func`.
Returns
-------
Nothing. The result is deliberately discarded to ensure that all cycles
are found.
assert_no_warnings(*args, **kwargs)
Fail if the given callable produces any warnings.
If called with all arguments omitted, may be used as a context manager::
with assert_no_warnings():
do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
.. versionadded:: 1.7.0
Parameters
----------
func : callable
The callable to test.
\*args : Arguments
Arguments passed to `func`.
\*\*kwargs : Kwargs
Keyword arguments passed to `func`.
Returns
-------
The value returned by `func`.
assert_raises(*args, **kwargs)
assert_raises(exception_class, callable, *args, **kwargs)
assert_raises(exception_class)
Fail unless an exception of class exception_class is thrown
by callable when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
Alternatively, `assert_raises` can be used as a context manager:
>>> from numpy.testing import assert_raises
>>> with assert_raises(ZeroDivisionError):
... 1 / 0
is equivalent to
>>> def div(x, y):
... return x / y
>>> assert_raises(ZeroDivisionError, div, 1, 0)
assert_raises_regex(exception_class, expected_regexp, *args, **kwargs)
assert_raises_regex(exception_class, expected_regexp, callable, *args,
**kwargs)
assert_raises_regex(exception_class, expected_regexp)
Fail unless an exception of class exception_class and with message that
matches expected_regexp is thrown by callable when invoked with arguments
args and keyword arguments kwargs.
Alternatively, can be used as a context manager like `assert_raises`.
Notes
-----
.. versionadded:: 1.9.0
assert_string_equal(actual, desired)
Test if two strings are equal.
If the given strings are equal, `assert_string_equal` does nothing.
If they are not equal, an AssertionError is raised, and the diff
between the strings is shown.
Parameters
----------
actual : str
The string to test for equality against the expected string.
desired : str
The expected string.
Examples
--------
>>> np.testing.assert_string_equal('abc', 'abc')
>>> np.testing.assert_string_equal('abc', 'abcd')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
AssertionError: Differences in strings:
- abc+ abcd? +
assert_warns(warning_class, *args, **kwargs)
Fail unless the given callable throws the specified warning.
A warning of class warning_class should be thrown by the callable when
invoked with arguments args and keyword arguments kwargs.
If a different type of warning is thrown, it will not be caught.
If called with all arguments other than the warning class omitted, may be
used as a context manager::
with assert_warns(SomeWarning):
do_something()
The ability to be used as a context manager is new in NumPy v1.11.0.
.. versionadded:: 1.4.0
Parameters
----------
warning_class : class
The class defining the warning that `func` is expected to throw.
func : callable, optional
Callable to test
*args : Arguments
Arguments for `func`.
**kwargs : Kwargs
Keyword arguments for `func`.
Returns
-------
The value returned by `func`.
Examples
--------
>>> import warnings
>>> def deprecated_func(num):
... warnings.warn("Please upgrade", DeprecationWarning)
... return num*num
>>> with np.testing.assert_warns(DeprecationWarning):
... assert deprecated_func(4) == 16
>>> # or passing a func
>>> ret = np.testing.assert_warns(DeprecationWarning, deprecated_func, 4)
>>> assert ret == 16
break_cycles()
Break reference cycles by calling gc.collect
Objects can call other objects' methods (for instance, another object's
__del__) inside their own __del__. On PyPy, the interpreter only runs
between calls to gc.collect, so multiple calls are needed to completely
release all cycles.
build_err_msg(arrays, err_msg, header='Items are not equal:', verbose=True, names=('ACTUAL', 'DESIRED'), precision=8)
check_support_sve(__cache=[])
gh-22982
decorate_methods(cls, decorator, testmatch=None)
Apply a decorator to all methods in a class matching a regular expression.
The given decorator is applied to all public methods of `cls` that are
matched by the regular expression `testmatch`
(``testmatch.search(methodname)``). Methods that are private, i.e. start
with an underscore, are ignored.
Parameters
----------
cls : class
Class whose methods to decorate.
decorator : function
Decorator to apply to methods
testmatch : compiled regexp or str, optional
The regular expression. Default value is None, in which case the
nose default (``re.compile(r'(?:^|[\b_\.%s-])[Tt]est' % os.sep)``)
is used.
If `testmatch` is a string, it is compiled to a regular expression
first.
jiffies(_load_time=[])
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user mode. See man 5 proc.
measure(code_str, times=1, label=None)
Return elapsed time for executing code in the namespace of the caller.
The supplied code string is compiled with the Python builtin ``compile``.
The precision of the timing is 10 milli-seconds. If the code will execute
fast on this timescale, it can be executed many times to get reasonable
timing accuracy.
Parameters
----------
code_str : str
The code to be timed.
times : int, optional
The number of times the code is executed. Default is 1. The code is
only compiled once.
label : str, optional
A label to identify `code_str` with. This is passed into ``compile``
as the second argument (for run-time error messages).
Returns
-------
elapsed : float
Total elapsed time in seconds for executing `code_str` `times` times.
Examples
--------
>>> times = 10
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times)
>>> print("Time for a single execution : ", etime / times, "s") # doctest: +SKIP
Time for a single execution : 0.005 s
memusage(processName='python', instance=0)
print_assert_equal(test_string, actual, desired)
Test if two objects are equal, and print an error message if test fails.
The test is performed with ``actual == desired``.
Parameters
----------
test_string : str
The message supplied to AssertionError.
actual : object
The object to test for equality against `desired`.
desired : object
The expected result.
Examples
--------
>>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 1])
>>> np.testing.print_assert_equal('Test XYZ of func xyz', [0, 1], [0, 2])
Traceback (most recent call last):
...
AssertionError: Test XYZ of func xyz failed
ACTUAL:
[0, 1]
DESIRED:
[0, 2]
run_threaded(func, iters, pass_count=False)
Runs a function many times in parallel
rundocs(filename=None, raise_on_error=True)
Run doctests found in the given file.
By default `rundocs` raises an AssertionError on failure.
Parameters
----------
filename : str
The path to the file for which the doctests are run.
raise_on_error : bool
Whether to raise an AssertionError when a doctest fails. Default is
True.
Notes
-----
The doctests can be run by the user/developer by adding the ``doctests``
argument to the ``test()`` call. For example, to run all tests (including
doctests) for ``numpy.lib``:
>>> np.lib.test(doctests=True) # doctest: +SKIP
runstring(astr, dict)
tempdir(*args, **kwargs)
Context manager to provide a temporary test folder.
All arguments are passed as this to the underlying tempfile.mkdtemp
function.
temppath(*args, **kwargs)
Context manager for temporary files.
Context manager that returns the path to a closed temporary file. Its
parameters are the same as for tempfile.mkstemp and are passed directly
to that function. The underlying file is removed when the context is
exited, so it should be closed at that time.
Windows does not allow a temporary file to be opened if it is already
open, so the underlying file must be closed after opening before it
can be opened again.
DATA
HAS_LAPACK64 = True
HAS_REFCOUNT = True
IS_EDITABLE = False
IS_MUSL = False
IS_PYPY = False
IS_PYSTON = False
IS_WASM = False
NOGIL_BUILD = False
__all__ = ['assert_equal', 'assert_almost_equal', 'assert_approx_equal...
verbose = 0
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\testing\__init__.py
numpy.tile
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
tile(A, reps)
Construct an array by repeating A the number of times given by reps.
If `reps` has length ``d``, the result will have dimension of
``max(d, A.ndim)``.
If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
or shape (1, 1, 3) for 3-D replication. If this is not the desired
behavior, promote `A` to d-dimensions manually before calling this
function.
If ``A.ndim > d``, `reps` is promoted to `A`.ndim by prepending 1's to it.
Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as
(1, 1, 2, 2).
Note : Although tile may be used for broadcasting, it is strongly
recommended to use numpy's broadcasting operations and functions.
Parameters
----------
A : array_like
The input array.
reps : array_like
The number of repetitions of `A` along each axis.
Returns
-------
c : ndarray
The tiled output array.
See Also
--------
repeat : Repeat elements of an array.
broadcast_to : Broadcast an array to a new shape
Examples
--------
>>> import numpy as np
>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
>>> np.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
[0, 1, 2, 0, 1, 2]])
>>> np.tile(a, (2, 1, 2))
array([[[0, 1, 2, 0, 1, 2]],
[[0, 1, 2, 0, 1, 2]]])
>>> b = np.array([[1, 2], [3, 4]])
>>> np.tile(b, 2)
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
>>> np.tile(b, (2, 1))
array([[1, 2],
[3, 4],
[1, 2],
[3, 4]])
>>> c = np.array([1,2,3,4])
>>> np.tile(c,(4,1))
array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
numpy.timedelta64
Python Library Documentation: class timedelta64 in module numpy class timedelta64(signedinteger) | A timedelta stored as a 64-bit integer. | | See :ref:`arrays.datetime` for more information. | | :Character code: ``'m'`` | | Method resolution order: | timedelta64 | signedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __str__(self, /) | Return str(self). | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __lshift__(self, value, /) | Return self<<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.trace
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)
Return the sum along diagonals of the array.
If `a` is 2-D, the sum along its diagonal with the given offset
is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
If `a` has more than two dimensions, then the axes specified by axis1 and
axis2 are used to determine the 2-D sub-arrays whose traces are returned.
The shape of the resulting array is the same as that of `a` with `axis1`
and `axis2` removed.
Parameters
----------
a : array_like
Input array, from which the diagonals are taken.
offset : int, optional
Offset of the diagonal from the main diagonal. Can be both positive
and negative. Defaults to 0.
axis1, axis2 : int, optional
Axes to be used as the first and second axis of the 2-D sub-arrays
from which the diagonals should be taken. Defaults are the first two
axes of `a`.
dtype : dtype, optional
Determines the data-type of the returned array and of the accumulator
where the elements are summed. If dtype has the value None and `a` is
of integer type of precision less than the default integer
precision, then the default integer precision is used. Otherwise,
the precision is the same as that of `a`.
out : ndarray, optional
Array into which the output is placed. Its type is preserved and
it must be of the right shape to hold the output.
Returns
-------
sum_along_diagonals : ndarray
If `a` is 2-D, the sum along the diagonal is returned. If `a` has
larger dimensions, then an array of sums along diagonals is returned.
See Also
--------
diag, diagonal, diagflat
Examples
--------
>>> import numpy as np
>>> np.trace(np.eye(3))
3.0
>>> a = np.arange(8).reshape((2,2,2))
>>> np.trace(a)
array([6, 8])
>>> a = np.arange(24).reshape((2,2,2,3))
>>> np.trace(a).shape
(2, 3)
numpy.transpose
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
transpose(a, axes=None)
Returns an array with axes transposed.
For a 1-D array, this returns an unchanged view of the original array, as a
transposed vector is simply the same vector.
To convert a 1-D array into a 2-D column vector, an additional dimension
must be added, e.g., ``np.atleast_2d(a).T`` achieves this, as does
``a[:, np.newaxis]``.
For a 2-D array, this is the standard matrix transpose.
For an n-D array, if axes are given, their order indicates how the
axes are permuted (see Examples). If axes are not provided, then
``transpose(a).shape == a.shape[::-1]``.
Parameters
----------
a : array_like
Input array.
axes : tuple or list of ints, optional
If specified, it must be a tuple or list which contains a permutation
of [0,1,...,N-1] where N is the number of axes of `a`. The `i`'th axis
of the returned array will correspond to the axis numbered ``axes[i]``
of the input. If not specified, defaults to ``range(a.ndim)[::-1]``,
which reverses the order of the axes.
Returns
-------
p : ndarray
`a` with its axes permuted. A view is returned whenever possible.
See Also
--------
ndarray.transpose : Equivalent method.
moveaxis : Move axes of an array to new positions.
argsort : Return the indices that would sort an array.
Notes
-----
Use ``transpose(a, argsort(axes))`` to invert the transposition of tensors
when using the `axes` keyword argument.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
[3, 4]])
>>> np.transpose(a)
array([[1, 3],
[2, 4]])
>>> a = np.array([1, 2, 3, 4])
>>> a
array([1, 2, 3, 4])
>>> np.transpose(a)
array([1, 2, 3, 4])
>>> a = np.ones((1, 2, 3))
>>> np.transpose(a, (1, 0, 2)).shape
(2, 1, 3)
>>> a = np.ones((2, 3, 4, 5))
>>> np.transpose(a).shape
(5, 4, 3, 2)
numpy.trapezoid
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
trapezoid(y, x=None, dx=1.0, axis=-1)
Integrate along the given axis using the composite trapezoidal rule.
If `x` is provided, the integration happens in sequence along its
elements - they are not sorted.
Integrate `y` (`x`) along each 1d slice on the given axis, compute
:math:`\int y(x) dx`.
When `x` is specified, this integrates along the parametric curve,
computing :math:`\int_t y(t) dt =
\int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.
.. versionadded:: 2.0.0
Parameters
----------
y : array_like
Input array to integrate.
x : array_like, optional
The sample points corresponding to the `y` values. If `x` is None,
the sample points are assumed to be evenly spaced `dx` apart. The
default is None.
dx : scalar, optional
The spacing between sample points when `x` is None. The default is 1.
axis : int, optional
The axis along which to integrate.
Returns
-------
trapezoid : float or ndarray
Definite integral of `y` = n-dimensional array as approximated along
a single axis by the trapezoidal rule. If `y` is a 1-dimensional array,
then the result is a float. If `n` is greater than 1, then the result
is an `n`-1 dimensional array.
See Also
--------
sum, cumsum
Notes
-----
Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
will be taken from `y` array, by default x-axis distances between
points will be 1.0, alternatively they can be provided with `x` array
or with `dx` scalar. Return value will be equal to combined area under
the red lines.
References
----------
.. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
.. [2] Illustration image:
https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
Examples
--------
>>> import numpy as np
Use the trapezoidal rule on evenly spaced points:
>>> np.trapezoid([1, 2, 3])
4.0
The spacing between sample points can be selected by either the
``x`` or ``dx`` arguments:
>>> np.trapezoid([1, 2, 3], x=[4, 6, 8])
8.0
>>> np.trapezoid([1, 2, 3], dx=2)
8.0
Using a decreasing ``x`` corresponds to integrating in reverse:
>>> np.trapezoid([1, 2, 3], x=[8, 6, 4])
-8.0
More generally ``x`` is used to integrate along a parametric curve. We can
estimate the integral :math:`\int_0^1 x^2 = 1/3` using:
>>> x = np.linspace(0, 1, num=50)
>>> y = x**2
>>> np.trapezoid(y, x)
0.33340274885464394
Or estimate the area of a circle, noting we repeat the sample which closes
the curve:
>>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
>>> np.trapezoid(np.cos(theta), x=np.sin(theta))
3.141571941375841
``np.trapezoid`` can be applied along a specified axis to do multiple
computations in one call:
>>> a = np.arange(6).reshape(2, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> np.trapezoid(a, axis=0)
array([1.5, 2.5, 3.5])
>>> np.trapezoid(a, axis=1)
array([2., 8.])
numpy.trapz
Python Library Documentation: function trapz in module numpy
trapz(y, x=None, dx=1.0, axis=-1)
`trapz` is deprecated in NumPy 2.0.
Please use `trapezoid` instead, or one of the numerical integration
functions in `scipy.integrate`.
numpy.tri
Python Library Documentation: function tri in module numpy
tri(N, M=None, k=0, dtype=<class 'float'>, *, like=None)
An array with ones at and below the given diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the array.
M : int, optional
Number of columns in the array.
By default, `M` is taken equal to `N`.
k : int, optional
The sub-diagonal at and below which the array is filled.
`k` = 0 is the main diagonal, while `k` < 0 is below it,
and `k` > 0 is above. The default is 0.
dtype : dtype, optional
Data type of the returned array. The default is float.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
tri : ndarray of shape (N, M)
Array with its lower triangle filled with ones and zero elsewhere;
in other words ``T[i,j] == 1`` for ``j <= i + k``, 0 otherwise.
Examples
--------
>>> import numpy as np
>>> np.tri(3, 5, 2, dtype=int)
array([[1, 1, 1, 0, 0],
[1, 1, 1, 1, 0],
[1, 1, 1, 1, 1]])
>>> np.tri(3, 5, -1)
array([[0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0.],
[1., 1., 0., 0., 0.]])
numpy.tril
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
tril(m, k=0)
Lower triangle of an array.
Return a copy of an array with elements above the `k`-th diagonal zeroed.
For arrays with ``ndim`` exceeding 2, `tril` will apply to the final two
axes.
Parameters
----------
m : array_like, shape (..., M, N)
Input array.
k : int, optional
Diagonal above which to zero elements. `k = 0` (the default) is the
main diagonal, `k < 0` is below it and `k > 0` is above.
Returns
-------
tril : ndarray, shape (..., M, N)
Lower triangle of `m`, of same shape and data-type as `m`.
See Also
--------
triu : same thing, only for the upper triangle
Examples
--------
>>> import numpy as np
>>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 0, 0, 0],
[ 4, 0, 0],
[ 7, 8, 0],
[10, 11, 12]])
>>> np.tril(np.arange(3*4*5).reshape(3, 4, 5))
array([[[ 0, 0, 0, 0, 0],
[ 5, 6, 0, 0, 0],
[10, 11, 12, 0, 0],
[15, 16, 17, 18, 0]],
[[20, 0, 0, 0, 0],
[25, 26, 0, 0, 0],
[30, 31, 32, 0, 0],
[35, 36, 37, 38, 0]],
[[40, 0, 0, 0, 0],
[45, 46, 0, 0, 0],
[50, 51, 52, 0, 0],
[55, 56, 57, 58, 0]]])
numpy.tril_indices
Python Library Documentation: function tril_indices in module numpy
tril_indices(n, k=0, m=None)
Return the indices for the lower-triangle of an (n, m) array.
Parameters
----------
n : int
The row dimension of the arrays for which the returned
indices will be valid.
k : int, optional
Diagonal offset (see `tril` for details).
m : int, optional
.. versionadded:: 1.9.0
The column dimension of the arrays for which the returned
arrays will be valid.
By default `m` is taken equal to `n`.
Returns
-------
inds : tuple of arrays
The indices for the triangle. The returned tuple contains two arrays,
each with the indices along one dimension of the array.
See also
--------
triu_indices : similar function, for upper-triangular.
mask_indices : generic function accepting an arbitrary mask function.
tril, triu
Notes
-----
.. versionadded:: 1.4.0
Examples
--------
>>> import numpy as np
Compute two different sets of indices to access 4x4 arrays, one for the
lower triangular part starting at the main diagonal, and one starting two
diagonals further right:
>>> il1 = np.tril_indices(4)
>>> il2 = np.tril_indices(4, 2)
Here is how they can be used with a sample array:
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Both for indexing:
>>> a[il1]
array([ 0, 4, 5, ..., 13, 14, 15])
And for assigning values:
>>> a[il1] = -1
>>> a
array([[-1, 1, 2, 3],
[-1, -1, 6, 7],
[-1, -1, -1, 11],
[-1, -1, -1, -1]])
These cover almost the whole array (two diagonals right of the main one):
>>> a[il2] = -10
>>> a
array([[-10, -10, -10, 3],
[-10, -10, -10, -10],
[-10, -10, -10, -10],
[-10, -10, -10, -10]])
numpy.tril_indices_from
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
tril_indices_from(arr, k=0)
Return the indices for the lower-triangle of arr.
See `tril_indices` for full details.
Parameters
----------
arr : array_like
The indices will be valid for square arrays whose dimensions are
the same as arr.
k : int, optional
Diagonal offset (see `tril` for details).
Examples
--------
>>> import numpy as np
Create a 4 by 4 array
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Pass the array to get the indices of the lower triangular elements.
>>> trili = np.tril_indices_from(a)
>>> trili
(array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3]))
>>> a[trili]
array([ 0, 4, 5, 8, 9, 10, 12, 13, 14, 15])
This is syntactic sugar for tril_indices().
>>> np.tril_indices(a.shape[0])
(array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3]), array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3]))
Use the `k` parameter to return the indices for the lower triangular array
up to the k-th diagonal.
>>> trili1 = np.tril_indices_from(a, k=1)
>>> a[trili1]
array([ 0, 1, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15])
See Also
--------
tril_indices, tril, triu_indices_from
Notes
-----
.. versionadded:: 1.4.0
numpy.trim_zeros
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
trim_zeros(filt, trim='fb')
Trim the leading and/or trailing zeros from a 1-D array or sequence.
Parameters
----------
filt : 1-D array or sequence
Input array.
trim : str, optional
A string with 'f' representing trim from front and 'b' to trim from
back. Default is 'fb', trim zeros from both front and back of the
array.
Returns
-------
trimmed : 1-D array or sequence
The result of trimming the input. The input data type is preserved.
Examples
--------
>>> import numpy as np
>>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0))
>>> np.trim_zeros(a)
array([1, 2, 3, 0, 2, 1])
>>> np.trim_zeros(a, 'b')
array([0, 0, 0, ..., 0, 2, 1])
The input data type is preserved, list/tuple in means list/tuple out.
>>> np.trim_zeros([0, 1, 2, 0])
[1, 2]
numpy.triu
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
triu(m, k=0)
Upper triangle of an array.
Return a copy of an array with the elements below the `k`-th diagonal
zeroed. For arrays with ``ndim`` exceeding 2, `triu` will apply to the
final two axes.
Please refer to the documentation for `tril` for further details.
See Also
--------
tril : lower triangle of an array
Examples
--------
>>> import numpy as np
>>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 0, 8, 9],
[ 0, 0, 12]])
>>> np.triu(np.arange(3*4*5).reshape(3, 4, 5))
array([[[ 0, 1, 2, 3, 4],
[ 0, 6, 7, 8, 9],
[ 0, 0, 12, 13, 14],
[ 0, 0, 0, 18, 19]],
[[20, 21, 22, 23, 24],
[ 0, 26, 27, 28, 29],
[ 0, 0, 32, 33, 34],
[ 0, 0, 0, 38, 39]],
[[40, 41, 42, 43, 44],
[ 0, 46, 47, 48, 49],
[ 0, 0, 52, 53, 54],
[ 0, 0, 0, 58, 59]]])
numpy.triu_indices
Python Library Documentation: function triu_indices in module numpy
triu_indices(n, k=0, m=None)
Return the indices for the upper-triangle of an (n, m) array.
Parameters
----------
n : int
The size of the arrays for which the returned indices will
be valid.
k : int, optional
Diagonal offset (see `triu` for details).
m : int, optional
.. versionadded:: 1.9.0
The column dimension of the arrays for which the returned
arrays will be valid.
By default `m` is taken equal to `n`.
Returns
-------
inds : tuple, shape(2) of ndarrays, shape(`n`)
The indices for the triangle. The returned tuple contains two arrays,
each with the indices along one dimension of the array. Can be used
to slice a ndarray of shape(`n`, `n`).
See also
--------
tril_indices : similar function, for lower-triangular.
mask_indices : generic function accepting an arbitrary mask function.
triu, tril
Notes
-----
.. versionadded:: 1.4.0
Examples
--------
>>> import numpy as np
Compute two different sets of indices to access 4x4 arrays, one for the
upper triangular part starting at the main diagonal, and one starting two
diagonals further right:
>>> iu1 = np.triu_indices(4)
>>> iu2 = np.triu_indices(4, 2)
Here is how they can be used with a sample array:
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Both for indexing:
>>> a[iu1]
array([ 0, 1, 2, ..., 10, 11, 15])
And for assigning values:
>>> a[iu1] = -1
>>> a
array([[-1, -1, -1, -1],
[ 4, -1, -1, -1],
[ 8, 9, -1, -1],
[12, 13, 14, -1]])
These cover only a small part of the whole array (two diagonals right
of the main one):
>>> a[iu2] = -10
>>> a
array([[ -1, -1, -10, -10],
[ 4, -1, -1, -10],
[ 8, 9, -1, -1],
[ 12, 13, 14, -1]])
numpy.triu_indices_from
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
triu_indices_from(arr, k=0)
Return the indices for the upper-triangle of arr.
See `triu_indices` for full details.
Parameters
----------
arr : ndarray, shape(N, N)
The indices will be valid for square arrays.
k : int, optional
Diagonal offset (see `triu` for details).
Returns
-------
triu_indices_from : tuple, shape(2) of ndarray, shape(N)
Indices for the upper-triangle of `arr`.
Examples
--------
>>> import numpy as np
Create a 4 by 4 array
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
Pass the array to get the indices of the upper triangular elements.
>>> triui = np.triu_indices_from(a)
>>> triui
(array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([0, 1, 2, 3, 1, 2, 3, 2, 3, 3]))
>>> a[triui]
array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15])
This is syntactic sugar for triu_indices().
>>> np.triu_indices(a.shape[0])
(array([0, 0, 0, 0, 1, 1, 1, 2, 2, 3]), array([0, 1, 2, 3, 1, 2, 3, 2, 3, 3]))
Use the `k` parameter to return the indices for the upper triangular array
from the k-th diagonal.
>>> triuim1 = np.triu_indices_from(a, k=1)
>>> a[triuim1]
array([ 1, 2, 3, 6, 7, 11])
See Also
--------
triu_indices, triu, tril_indices_from
Notes
-----
.. versionadded:: 1.4.0
numpy.true_divide
Python Library Documentation: ufunc
divide = <ufunc 'divide'>
divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Divide arguments element-wise.
Parameters
----------
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
If ``x1.shape != x2.shape``, they must be broadcastable to a common
shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The quotient ``x1/x2``, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
See Also
--------
seterr : Set whether to raise or warn on overflow, underflow and
division by zero.
Notes
-----
Equivalent to ``x1`` / ``x2`` in terms of array-broadcasting.
The ``true_divide(x1, x2)`` function is an alias for
``divide(x1, x2)``.
Examples
--------
>>> import numpy as np
>>> np.divide(2.0, 4.0)
0.5
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.divide(x1, x2)
array([[nan, 1. , 1. ],
[inf, 4. , 2.5],
[inf, 7. , 4. ]])
The ``/`` operator can be used as a shorthand for ``np.divide`` on
ndarrays.
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = 2 * np.ones(3)
>>> x1 / x2
array([[0. , 0.5, 1. ],
[1.5, 2. , 2.5],
[3. , 3.5, 4. ]])
numpy.trunc
Python Library Documentation: ufunc
trunc = <ufunc 'trunc'>
trunc(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature])
Return the truncated value of the input, element-wise.
The truncated value of the scalar `x` is the nearest integer `i` which
is closer to zero than `x` is. In short, the fractional part of the
signed number `x` is discarded.
Parameters
----------
x : array_like
Input data.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray or scalar
The truncated value of each element in `x`.
This is a scalar if `x` is a scalar.
See Also
--------
ceil, floor, rint, fix
Notes
-----
.. versionadded:: 1.3.0
Examples
--------
>>> import numpy as np
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.trunc(a)
array([-1., -1., -0., 0., 1., 1., 2.])
numpy.typecodes
Python Library Documentation: dict object
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
|
| Built-in subclasses:
| StgDict
|
| Methods defined here:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
numpy.typename
Python Library Documentation: function typename in module numpy
typename(char)
Return a description for the given data type code.
Parameters
----------
char : str
Data type code.
Returns
-------
out : str
Description of the input data type code.
See Also
--------
dtype
Examples
--------
>>> import numpy as np
>>> typechars = ['S1', '?', 'B', 'D', 'G', 'F', 'I', 'H', 'L', 'O', 'Q',
... 'S', 'U', 'V', 'b', 'd', 'g', 'f', 'i', 'h', 'l', 'q']
>>> for typechar in typechars:
... print(typechar, ' : ', np.typename(typechar))
...
S1 : character
? : bool
B : unsigned char
D : complex double precision
G : complex long double precision
F : complex single precision
I : unsigned integer
H : unsigned short
L : unsigned long integer
O : object
Q : unsigned long long integer
S : string
U : unicode
V : void
b : signed char
d : double precision
g : long precision
f : single precision
i : integer
h : short
l : long integer
q : long long integer
numpy.typing
Python Library Documentation: package numpy.typing in numpy
NAME
numpy.typing
DESCRIPTION
============================
Typing (:mod:`numpy.typing`)
============================
.. versionadded:: 1.20
Large parts of the NumPy API have :pep:`484`-style type annotations. In
addition a number of type aliases are available to users, most prominently
the two below:
- `ArrayLike`: objects that can be converted to arrays
- `DTypeLike`: objects that can be converted to dtypes
.. _typing-extensions: https://pypi.org/project/typing-extensions/
Mypy plugin
-----------
.. versionadded:: 1.21
.. automodule:: numpy.typing.mypy_plugin
.. currentmodule:: numpy.typing
Differences from the runtime NumPy API
--------------------------------------
NumPy is very flexible. Trying to describe the full range of
possibilities statically would result in types that are not very
helpful. For that reason, the typed NumPy API is often stricter than
the runtime NumPy API. This section describes some notable
differences.
ArrayLike
~~~~~~~~~
The `ArrayLike` type tries to avoid creating object arrays. For
example,
.. code-block:: python
>>> np.array(x**2 for x in range(10))
array(<generator object <genexpr> at ...>, dtype=object)
is valid NumPy code which will create a 0-dimensional object
array. Type checkers will complain about the above example when using
the NumPy types however. If you really intended to do the above, then
you can either use a ``# type: ignore`` comment:
.. code-block:: python
>>> np.array(x**2 for x in range(10)) # type: ignore
or explicitly type the array like object as `~typing.Any`:
.. code-block:: python
>>> from typing import Any
>>> array_like: Any = (x**2 for x in range(10))
>>> np.array(array_like)
array(<generator object <genexpr> at ...>, dtype=object)
ndarray
~~~~~~~
It's possible to mutate the dtype of an array at runtime. For example,
the following code is valid:
.. code-block:: python
>>> x = np.array([1, 2])
>>> x.dtype = np.bool
This sort of mutation is not allowed by the types. Users who want to
write statically typed code should instead use the `numpy.ndarray.view`
method to create a view of the array with a different dtype.
DTypeLike
~~~~~~~~~
The `DTypeLike` type tries to avoid creation of dtype objects using
dictionary of fields like below:
.. code-block:: python
>>> x = np.dtype({"field1": (float, 1), "field2": (int, 3)})
Although this is valid NumPy code, the type checker will complain about it,
since its usage is discouraged.
Please see : :ref:`Data type objects <arrays.dtypes>`
Number precision
~~~~~~~~~~~~~~~~
The precision of `numpy.number` subclasses is treated as a invariant generic
parameter (see :class:`~NBitBase`), simplifying the annotating of processes
involving precision-based casting.
.. code-block:: python
>>> from typing import TypeVar
>>> import numpy as np
>>> import numpy.typing as npt
>>> T = TypeVar("T", bound=npt.NBitBase)
>>> def func(a: "np.floating[T]", b: "np.floating[T]") -> "np.floating[T]":
... ...
Consequently, the likes of `~numpy.float16`, `~numpy.float32` and
`~numpy.float64` are still sub-types of `~numpy.floating`, but, contrary to
runtime, they're not necessarily considered as sub-classes.
Timedelta64
~~~~~~~~~~~
The `~numpy.timedelta64` class is not considered a subclass of
`~numpy.signedinteger`, the former only inheriting from `~numpy.generic`
while static type checking.
0D arrays
~~~~~~~~~
During runtime numpy aggressively casts any passed 0D arrays into their
corresponding `~numpy.generic` instance. Until the introduction of shape
typing (see :pep:`646`) it is unfortunately not possible to make the
necessary distinction between 0D and >0D arrays. While thus not strictly
correct, all operations are that can potentially perform a 0D-array -> scalar
cast are currently annotated as exclusively returning an `~numpy.ndarray`.
If it is known in advance that an operation *will* perform a
0D-array -> scalar cast, then one can consider manually remedying the
situation with either `typing.cast` or a ``# type: ignore`` comment.
Record array dtypes
~~~~~~~~~~~~~~~~~~~
The dtype of `numpy.recarray`, and the :ref:`routines.array-creation.rec`
functions in general, can be specified in one of two ways:
* Directly via the ``dtype`` argument.
* With up to five helper arguments that operate via `numpy.rec.format_parser`:
``formats``, ``names``, ``titles``, ``aligned`` and ``byteorder``.
These two approaches are currently typed as being mutually exclusive,
*i.e.* if ``dtype`` is specified than one may not specify ``formats``.
While this mutual exclusivity is not (strictly) enforced during runtime,
combining both dtype specifiers can lead to unexpected or even downright
buggy behavior.
API
---
.. data:: ArrayLike
:value: typing.Union[...]
A `~typing.Union` representing objects that can be coerced
into an `~numpy.ndarray`.
Among others this includes the likes of:
* Scalars.
* (Nested) sequences.
* Objects implementing the `~class.__array__` protocol.
.. versionadded:: 1.20
.. admonition:: See Also
:term:`array_like`:
Any scalar or sequence that can be interpreted as an ndarray.
.. rubric:: Examples
.. code-block:: python
>>> import numpy as np
>>> import numpy.typing as npt
>>> def as_array(a: npt.ArrayLike) -> np.ndarray:
... return np.array(a)
.. data:: DTypeLike
:value: typing.Union[...]
A `~typing.Union` representing objects that can be coerced
into a `~numpy.dtype`.
Among others this includes the likes of:
* :class:`type` objects.
* Character codes or the names of :class:`type` objects.
* Objects with the ``.dtype`` attribute.
.. versionadded:: 1.20
.. admonition:: See Also
:ref:`Specifying and constructing data types <arrays.dtypes.constructing>`
A comprehensive overview of all objects that can be coerced
into data types.
.. rubric:: Examples
.. code-block:: python
>>> import numpy as np
>>> import numpy.typing as npt
>>> def as_dtype(d: npt.DTypeLike) -> np.dtype:
... return np.dtype(d)
.. data:: NDArray
:value: numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
A `np.ndarray[Any, np.dtype[+ScalarType]] <numpy.ndarray>` type alias
:term:`generic <generic type>` w.r.t. its `dtype.type <numpy.dtype.type>`.
Can be used during runtime for typing arrays with a given dtype
and unspecified shape.
.. versionadded:: 1.21
.. rubric:: Examples
.. code-block:: python
>>> import numpy as np
>>> import numpy.typing as npt
>>> print(npt.NDArray)
numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
>>> print(npt.NDArray[np.float64])
numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
>>> NDArrayInt = npt.NDArray[np.int_]
>>> a: NDArrayInt = np.arange(10)
>>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:
... return np.array(a)
.. autoclass:: numpy.typing.NBitBase
PACKAGE CONTENTS
mypy_plugin
tests (package)
CLASSES
builtins.object
NBitBase
class NBitBase(builtins.object)
| A type representing `numpy.number` precision during static type checking.
|
| Used exclusively for the purpose static type checking, `NBitBase`
| represents the base of a hierarchical set of subclasses.
| Each subsequent subclass is herein used for representing a lower level
| of precision, *e.g.* ``64Bit > 32Bit > 16Bit``.
|
| .. versionadded:: 1.20
|
| Examples
| --------
| Below is a typical usage example: `NBitBase` is herein used for annotating
| a function that takes a float and integer of arbitrary precision
| as arguments and returns a new float of whichever precision is largest
| (*e.g.* ``np.float16 + np.int64 -> np.float64``).
|
| .. code-block:: python
|
| >>> from __future__ import annotations
| >>> from typing import TypeVar, TYPE_CHECKING
| >>> import numpy as np
| >>> import numpy.typing as npt
|
| >>> T1 = TypeVar("T1", bound=npt.NBitBase)
| >>> T2 = TypeVar("T2", bound=npt.NBitBase)
|
| >>> def add(a: np.floating[T1], b: np.integer[T2]) -> np.floating[T1 | T2]:
| ... return a + b
|
| >>> a = np.float16()
| >>> b = np.int64()
| >>> out = add(a, b)
|
| >>> if TYPE_CHECKING:
| ... reveal_locals()
| ... # note: Revealed local types are:
| ... # note: a: numpy.floating[numpy.typing._16Bit*]
| ... # note: b: numpy.signedinteger[numpy.typing._64Bit*]
| ... # note: out: numpy.floating[numpy.typing._64Bit*]
|
| Class methods defined here:
|
| __init_subclass__() -> 'None' from numpy._typing.NBitBase
| This method is called when a class is subclassed.
|
| The default implementation does nothing. It may be
| overridden to extend subclasses.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __final__ = True
DATA
ArrayLike = typing.Union[collections.abc.Buffer, numpy._typi...ence[bo...
DTypeLike = typing.Union[numpy.dtype[typing.Any], NoneType, ...e_like....
NDArray = numpy.ndarray[typing.Any, numpy.dtype[+_ScalarType_co]]
__all__ = ['ArrayLike', 'DTypeLike', 'NBitBase', 'NDArray']
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\numpy\typing\__init__.py
numpy.ubyte
Python Library Documentation: class uint8 in module numpy class uint8(unsignedinteger) | Unsigned integer type, compatible with C ``unsigned char``. | | :Character code: ``'B'`` | :Canonical name: `numpy.ubyte` | :Alias on this platform (win32 AMD64): `numpy.uint8`: 8-bit unsigned integer (``0`` to ``255``). | | Method resolution order: | uint8 | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | uint8.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.uint8(127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.ufunc
Python Library Documentation: class ufunc in module numpy
class ufunc(builtins.object)
| Functions that operate element by element on whole arrays.
|
| To see the documentation for a specific ufunc, use `info`. For
| example, ``np.info(np.sin)``. Because ufuncs are written in C
| (for speed) and linked into Python with NumPy's ufunc facility,
| Python's help() function finds this page whenever help() is called
| on a ufunc.
|
| A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.
|
| **Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)``
|
| Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.
|
| The broadcasting rules are:
|
| * Dimensions of length 1 may be prepended to either array.
| * Arrays may be repeated along dimensions of length 1.
|
| Parameters
| ----------
| *x : array_like
| Input arrays.
| out : ndarray, None, or tuple of ndarray and None, optional
| Alternate array object(s) in which to put the result; if provided, it
| must have a shape that the inputs broadcast to. A tuple of arrays
| (possible only as a keyword argument) must have length equal to the
| number of outputs; use None for uninitialized outputs to be
| allocated by the ufunc.
| where : array_like, optional
| This condition is broadcast over the input. At locations where the
| condition is True, the `out` array will be set to the ufunc result.
| Elsewhere, the `out` array will retain its original value.
| Note that if an uninitialized `out` array is created via the default
| ``out=None``, locations within it where the condition is False will
| remain uninitialized.
| **kwargs
| For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.
|
| Returns
| -------
| r : ndarray or tuple of ndarray
| `r` will have the shape that the arrays in `x` broadcast to; if `out` is
| provided, it will be returned. If not, `r` will be allocated and
| may contain uninitialized values. If the function has more than one
| output, then the result will be a tuple of arrays.
|
| Methods defined here:
|
| __call__(self, /, *args, **kwargs)
| Call self as a function.
|
| __repr__(self, /)
| Return repr(self).
|
| __str__(self, /)
| Return str(self).
|
| accumulate(...)
| accumulate(array, axis=0, dtype=None, out=None)
|
| Accumulate the result of applying the operator to all elements.
|
| For a one-dimensional array, accumulate produces results equivalent to::
|
| r = np.empty(len(A))
| t = op.identity # op = the ufunc being applied to A's elements
| for i in range(len(A)):
| t = op(t, A[i])
| r[i] = t
| return r
|
| For example, add.accumulate() is equivalent to np.cumsum().
|
| For a multi-dimensional array, accumulate is applied along only one
| axis (axis zero by default; see Examples below) so repeated use is
| necessary if one wants to accumulate over multiple axes.
|
| Parameters
| ----------
| array : array_like
| The array to act on.
| axis : int, optional
| The axis along which to apply the accumulation; default is zero.
| dtype : data-type code, optional
| The data-type used to represent the intermediate results. Defaults
| to the data-type of the output array if such is provided, or the
| data-type of the input array if no output array is provided.
| out : ndarray, None, or tuple of ndarray and None, optional
| A location into which the result is stored. If not provided or None,
| a freshly-allocated array is returned. For consistency with
| ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
| 1-element tuple.
|
| .. versionchanged:: 1.13.0
| Tuples are allowed for keyword argument.
|
| Returns
| -------
| r : ndarray
| The accumulated values. If `out` was supplied, `r` is a reference to
| `out`.
|
| Examples
| --------
| 1-D array examples:
|
| >>> import numpy as np
| >>> np.add.accumulate([2, 3, 5])
| array([ 2, 5, 10])
| >>> np.multiply.accumulate([2, 3, 5])
| array([ 2, 6, 30])
|
| 2-D array examples:
|
| >>> I = np.eye(2)
| >>> I
| array([[1., 0.],
| [0., 1.]])
|
| Accumulate along axis 0 (rows), down columns:
|
| >>> np.add.accumulate(I, 0)
| array([[1., 0.],
| [1., 1.]])
| >>> np.add.accumulate(I) # no axis specified = axis zero
| array([[1., 0.],
| [1., 1.]])
|
| Accumulate along axis 1 (columns), through rows:
|
| >>> np.add.accumulate(I, 1)
| array([[1., 1.],
| [0., 1.]])
|
| at(...)
| at(a, indices, b=None, /)
|
| Performs unbuffered in place operation on operand 'a' for elements
| specified by 'indices'. For addition ufunc, this method is equivalent to
| ``a[indices] += b``, except that results are accumulated for elements that
| are indexed more than once. For example, ``a[[0,0]] += 1`` will only
| increment the first element once because of buffering, whereas
| ``add.at(a, [0,0], 1)`` will increment the first element twice.
|
| .. versionadded:: 1.8.0
|
| Parameters
| ----------
| a : array_like
| The array to perform in place operation on.
| indices : array_like or tuple
| Array like index object or slice object for indexing into first
| operand. If first operand has multiple dimensions, indices can be a
| tuple of array like index objects or slice objects.
| b : array_like
| Second operand for ufuncs requiring two operands. Operand must be
| broadcastable over first operand after indexing or slicing.
|
| Examples
| --------
| Set items 0 and 1 to their negative values:
|
| >>> import numpy as np
| >>> a = np.array([1, 2, 3, 4])
| >>> np.negative.at(a, [0, 1])
| >>> a
| array([-1, -2, 3, 4])
|
| Increment items 0 and 1, and increment item 2 twice:
|
| >>> a = np.array([1, 2, 3, 4])
| >>> np.add.at(a, [0, 1, 2, 2], 1)
| >>> a
| array([2, 3, 5, 4])
|
| Add items 0 and 1 in first array to second array,
| and store results in first array:
|
| >>> a = np.array([1, 2, 3, 4])
| >>> b = np.array([1, 2])
| >>> np.add.at(a, [0, 1], b)
| >>> a
| array([2, 4, 3, 4])
|
| outer(...)
| outer(A, B, /, **kwargs)
|
| Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.
|
| Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of
| ``op.outer(A, B)`` is an array of dimension M + N such that:
|
| .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] =
| op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}])
|
| For `A` and `B` one-dimensional, this is equivalent to::
|
| r = empty(len(A),len(B))
| for i in range(len(A)):
| for j in range(len(B)):
| r[i,j] = op(A[i], B[j]) # op = ufunc in question
|
| Parameters
| ----------
| A : array_like
| First array
| B : array_like
| Second array
| kwargs : any
| Arguments to pass on to the ufunc. Typically `dtype` or `out`.
| See `ufunc` for a comprehensive overview of all available arguments.
|
| Returns
| -------
| r : ndarray
| Output array
|
| See Also
| --------
| numpy.outer : A less powerful version of ``np.multiply.outer``
| that `ravel`\ s all inputs to 1D. This exists
| primarily for compatibility with old code.
|
| tensordot : ``np.tensordot(a, b, axes=((), ()))`` and
| ``np.multiply.outer(a, b)`` behave same for all
| dimensions of a and b.
|
| Examples
| --------
| >>> np.multiply.outer([1, 2, 3], [4, 5, 6])
| array([[ 4, 5, 6],
| [ 8, 10, 12],
| [12, 15, 18]])
|
| A multi-dimensional example:
|
| >>> A = np.array([[1, 2, 3], [4, 5, 6]])
| >>> A.shape
| (2, 3)
| >>> B = np.array([[1, 2, 3, 4]])
| >>> B.shape
| (1, 4)
| >>> C = np.multiply.outer(A, B)
| >>> C.shape; C
| (2, 3, 1, 4)
| array([[[[ 1, 2, 3, 4]],
| [[ 2, 4, 6, 8]],
| [[ 3, 6, 9, 12]]],
| [[[ 4, 8, 12, 16]],
| [[ 5, 10, 15, 20]],
| [[ 6, 12, 18, 24]]]])
|
| reduce(...)
| reduce(array, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True)
|
| Reduces `array`'s dimension by one, by applying ufunc along one axis.
|
| Let :math:`array.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then
| :math:`ufunc.reduce(array, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` =
| the result of iterating `j` over :math:`range(N_i)`, cumulatively applying
| ufunc to each :math:`array[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`.
| For a one-dimensional array, reduce produces results equivalent to:
| ::
|
| r = op.identity # op = ufunc
| for i in range(len(A)):
| r = op(r, A[i])
| return r
|
| For example, add.reduce() is equivalent to sum().
|
| Parameters
| ----------
| array : array_like
| The array to act on.
| axis : None or int or tuple of ints, optional
| Axis or axes along which a reduction is performed.
| The default (`axis` = 0) is perform a reduction over the first
| dimension of the input array. `axis` may be negative, in
| which case it counts from the last to the first axis.
|
| .. versionadded:: 1.7.0
|
| If this is None, a reduction is performed over all the axes.
| If this is a tuple of ints, a reduction is performed on multiple
| axes, instead of a single axis or all the axes as before.
|
| For operations which are either not commutative or not associative,
| doing a reduction over multiple axes is not well-defined. The
| ufuncs do not currently raise an exception in this case, but will
| likely do so in the future.
| dtype : data-type code, optional
| The data type used to perform the operation. Defaults to that of
| ``out`` if given, and the data type of ``array`` otherwise (though
| upcast to conserve precision for some cases, such as
| ``numpy.add.reduce`` for integer or boolean input).
| out : ndarray, None, or tuple of ndarray and None, optional
| A location into which the result is stored. If not provided or None,
| a freshly-allocated array is returned. For consistency with
| ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
| 1-element tuple.
|
| .. versionchanged:: 1.13.0
| Tuples are allowed for keyword argument.
| keepdims : bool, optional
| If this is set to True, the axes which are reduced are left
| in the result as dimensions with size one. With this option,
| the result will broadcast correctly against the original `array`.
|
| .. versionadded:: 1.7.0
| initial : scalar, optional
| The value with which to start the reduction.
| If the ufunc has no identity or the dtype is object, this defaults
| to None - otherwise it defaults to ufunc.identity.
| If ``None`` is given, the first element of the reduction is used,
| and an error is thrown if the reduction is empty.
|
| .. versionadded:: 1.15.0
|
| where : array_like of bool, optional
| A boolean array which is broadcasted to match the dimensions
| of `array`, and selects elements to include in the reduction. Note
| that for ufuncs like ``minimum`` that do not have an identity
| defined, one has to pass in also ``initial``.
|
| .. versionadded:: 1.17.0
|
| Returns
| -------
| r : ndarray
| The reduced array. If `out` was supplied, `r` is a reference to it.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.multiply.reduce([2,3,5])
| 30
|
| A multi-dimensional array example:
|
| >>> X = np.arange(8).reshape((2,2,2))
| >>> X
| array([[[0, 1],
| [2, 3]],
| [[4, 5],
| [6, 7]]])
| >>> np.add.reduce(X, 0)
| array([[ 4, 6],
| [ 8, 10]])
| >>> np.add.reduce(X) # confirm: default axis value is 0
| array([[ 4, 6],
| [ 8, 10]])
| >>> np.add.reduce(X, 1)
| array([[ 2, 4],
| [10, 12]])
| >>> np.add.reduce(X, 2)
| array([[ 1, 5],
| [ 9, 13]])
|
| You can use the ``initial`` keyword argument to initialize the reduction
| with a different value, and ``where`` to select specific elements to include:
|
| >>> np.add.reduce([10], initial=5)
| 15
| >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)
| array([14., 14.])
| >>> a = np.array([10., np.nan, 10])
| >>> np.add.reduce(a, where=~np.isnan(a))
| 20.0
|
| Allows reductions of empty arrays where they would normally fail, i.e.
| for ufuncs without an identity.
|
| >>> np.minimum.reduce([], initial=np.inf)
| inf
| >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])
| array([ 1., 10.])
| >>> np.minimum.reduce([])
| Traceback (most recent call last):
| ...
| ValueError: zero-size array to reduction operation minimum which has no identity
|
| reduceat(...)
| reduceat(array, indices, axis=0, dtype=None, out=None)
|
| Performs a (local) reduce with specified slices over a single axis.
|
| For i in ``range(len(indices))``, `reduceat` computes
| ``ufunc.reduce(array[indices[i]:indices[i+1]])``, which becomes the i-th
| generalized "row" parallel to `axis` in the final result (i.e., in a
| 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if
| `axis = 1`, it becomes the i-th column). There are three exceptions to this:
|
| * when ``i = len(indices) - 1`` (so for the last index),
| ``indices[i+1] = array.shape[axis]``.
| * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is
| simply ``array[indices[i]]``.
| * if ``indices[i] >= len(array)`` or ``indices[i] < 0``, an error is raised.
|
| The shape of the output depends on the size of `indices`, and may be
| larger than `array` (this happens if ``len(indices) > array.shape[axis]``).
|
| Parameters
| ----------
| array : array_like
| The array to act on.
| indices : array_like
| Paired indices, comma separated (not colon), specifying slices to
| reduce.
| axis : int, optional
| The axis along which to apply the reduceat.
| dtype : data-type code, optional
| The data type used to perform the operation. Defaults to that of
| ``out`` if given, and the data type of ``array`` otherwise (though
| upcast to conserve precision for some cases, such as
| ``numpy.add.reduce`` for integer or boolean input).
| out : ndarray, None, or tuple of ndarray and None, optional
| A location into which the result is stored. If not provided or None,
| a freshly-allocated array is returned. For consistency with
| ``ufunc.__call__``, if given as a keyword, this may be wrapped in a
| 1-element tuple.
|
| .. versionchanged:: 1.13.0
| Tuples are allowed for keyword argument.
|
| Returns
| -------
| r : ndarray
| The reduced values. If `out` was supplied, `r` is a reference to
| `out`.
|
| Notes
| -----
| A descriptive example:
|
| If `array` is 1-D, the function `ufunc.accumulate(array)` is the same as
| ``ufunc.reduceat(array, indices)[::2]`` where `indices` is
| ``range(len(array) - 1)`` with a zero placed
| in every other element:
| ``indices = zeros(2 * len(array) - 1)``,
| ``indices[1::2] = range(1, len(array))``.
|
| Don't be fooled by this attribute's name: `reduceat(array)` is not
| necessarily smaller than `array`.
|
| Examples
| --------
| To take the running sum of four successive values:
|
| >>> import numpy as np
| >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]
| array([ 6, 10, 14, 18])
|
| A 2-D example:
|
| >>> x = np.linspace(0, 15, 16).reshape(4,4)
| >>> x
| array([[ 0., 1., 2., 3.],
| [ 4., 5., 6., 7.],
| [ 8., 9., 10., 11.],
| [12., 13., 14., 15.]])
|
| ::
|
| # reduce such that the result has the following five rows:
| # [row1 + row2 + row3]
| # [row4]
| # [row2]
| # [row3]
| # [row1 + row2 + row3 + row4]
|
| >>> np.add.reduceat(x, [0, 3, 1, 2, 0])
| array([[12., 15., 18., 21.],
| [12., 13., 14., 15.],
| [ 4., 5., 6., 7.],
| [ 8., 9., 10., 11.],
| [24., 28., 32., 36.]])
|
| ::
|
| # reduce such that result has the following two columns:
| # [col1 * col2 * col3, col4]
|
| >>> np.multiply.reduceat(x, [0, 3], 1)
| array([[ 0., 3.],
| [ 120., 7.],
| [ 720., 11.],
| [2184., 15.]])
|
| resolve_dtypes(...)
| resolve_dtypes(dtypes, *, signature=None, casting=None, reduction=False)
|
| Find the dtypes NumPy will use for the operation. Both input and
| output dtypes are returned and may differ from those provided.
|
| .. note::
|
| This function always applies NEP 50 rules since it is not provided
| any actual values. The Python types ``int``, ``float``, and
| ``complex`` thus behave weak and should be passed for "untyped"
| Python input.
|
| Parameters
| ----------
| dtypes : tuple of dtypes, None, or literal int, float, complex
| The input dtypes for each operand. Output operands can be
| None, indicating that the dtype must be found.
| signature : tuple of DTypes or None, optional
| If given, enforces exact DType (classes) of the specific operand.
| The ufunc ``dtype`` argument is equivalent to passing a tuple with
| only output dtypes set.
| casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
| The casting mode when casting is necessary. This is identical to
| the ufunc call casting modes.
| reduction : boolean
| If given, the resolution assumes a reduce operation is happening
| which slightly changes the promotion and type resolution rules.
| `dtypes` is usually something like ``(None, np.dtype("i2"), None)``
| for reductions (first input is also the output).
|
| .. note::
|
| The default casting mode is "same_kind", however, as of
| NumPy 1.24, NumPy uses "unsafe" for reductions.
|
| Returns
| -------
| dtypes : tuple of dtypes
| The dtypes which NumPy would use for the calculation. Note that
| dtypes may not match the passed in ones (casting is necessary).
|
|
| Examples
| --------
| This API requires passing dtypes, define them for convenience:
|
| >>> import numpy as np
| >>> int32 = np.dtype("int32")
| >>> float32 = np.dtype("float32")
|
| The typical ufunc call does not pass an output dtype. `numpy.add` has two
| inputs and one output, so leave the output as ``None`` (not provided):
|
| >>> np.add.resolve_dtypes((int32, float32, None))
| (dtype('float64'), dtype('float64'), dtype('float64'))
|
| The loop found uses "float64" for all operands (including the output), the
| first input would be cast.
|
| ``resolve_dtypes`` supports "weak" handling for Python scalars by passing
| ``int``, ``float``, or ``complex``:
|
| >>> np.add.resolve_dtypes((float32, float, None))
| (dtype('float32'), dtype('float32'), dtype('float32'))
|
| Where the Python ``float`` behaves samilar to a Python value ``0.0``
| in a ufunc call. (See :ref:`NEP 50 <NEP50>` for details.)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| identity
| The identity value.
|
| Data attribute containing the identity element for the ufunc,
| if it has one. If it does not, the attribute value is None.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.add.identity
| 0
| >>> np.multiply.identity
| 1
| >>> np.power.identity
| 1
| >>> print(np.exp.identity)
| None
|
| nargs
| The number of arguments.
|
| Data attribute containing the number of arguments the ufunc takes, including
| optional ones.
|
| Notes
| -----
| Typically this value will be one more than what you might expect
| because all ufuncs take the optional "out" argument.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.add.nargs
| 3
| >>> np.multiply.nargs
| 3
| >>> np.power.nargs
| 3
| >>> np.exp.nargs
| 2
|
| nin
| The number of inputs.
|
| Data attribute containing the number of arguments the ufunc treats as input.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.add.nin
| 2
| >>> np.multiply.nin
| 2
| >>> np.power.nin
| 2
| >>> np.exp.nin
| 1
|
| nout
| The number of outputs.
|
| Data attribute containing the number of arguments the ufunc treats as output.
|
| Notes
| -----
| Since all ufuncs can take output arguments, this will always be at least 1.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.add.nout
| 1
| >>> np.multiply.nout
| 1
| >>> np.power.nout
| 1
| >>> np.exp.nout
| 1
|
| ntypes
| The number of types.
|
| The number of numerical NumPy types - of which there are 18 total - on which
| the ufunc can operate.
|
| See Also
| --------
| numpy.ufunc.types
|
| Examples
| --------
| >>> import numpy as np
| >>> np.add.ntypes
| 18
| >>> np.multiply.ntypes
| 18
| >>> np.power.ntypes
| 17
| >>> np.exp.ntypes
| 7
| >>> np.remainder.ntypes
| 14
|
| signature
| Definition of the core elements a generalized ufunc operates on.
|
| The signature determines how the dimensions of each input/output array
| are split into core and loop dimensions:
|
| 1. Each dimension in the signature is matched to a dimension of the
| corresponding passed-in array, starting from the end of the shape tuple.
| 2. Core dimensions assigned to the same label in the signature must have
| exactly matching sizes, no broadcasting is performed.
| 3. The core dimensions are removed from all inputs and the remaining
| dimensions are broadcast together, defining the loop dimensions.
|
| Notes
| -----
| Generalized ufuncs are used internally in many linalg functions, and in
| the testing suite; the examples below are taken from these.
| For ufuncs that operate on scalars, the signature is None, which is
| equivalent to '()' for every argument.
|
| Examples
| --------
| >>> import numpy as np
| >>> np.linalg._umath_linalg.det.signature
| '(m,m)->()'
| >>> np.matmul.signature
| '(n?,k),(k,m?)->(n?,m?)'
| >>> np.add.signature is None
| True # equivalent to '(),()->()'
|
| types
| Returns a list with types grouped input->output.
|
| Data attribute listing the data-type "Domain-Range" groupings the ufunc can
| deliver. The data-types are given using the character codes.
|
| See Also
| --------
| numpy.ufunc.ntypes
|
| Examples
| --------
| >>> import numpy as np
| >>> np.add.types
| ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
| 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',
| 'GG->G', 'OO->O']
|
| >>> np.multiply.types
| ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',
| 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',
| 'GG->G', 'OO->O']
|
| >>> np.power.types
| ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',
| 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G',
| 'OO->O']
|
| >>> np.exp.types
| ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O']
|
| >>> np.remainder.types
| ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',
| 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O']
numpy.uint
Python Library Documentation: class uint64 in module numpy class uint64(unsignedinteger) | Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit | systems. | | :Character code: ``'Q'`` | :Canonical name: `numpy.uint` | :Alias on this platform (win32 AMD64): `numpy.uint64`: 64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``). | :Alias on this platform (win32 AMD64): `numpy.uintp`: Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``. | | Method resolution order: | uint64 | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | uint64.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.uint64(127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.uint16
Python Library Documentation: class uint16 in module numpy class uint16(unsignedinteger) | Unsigned integer type, compatible with C ``unsigned short``. | | :Character code: ``'H'`` | :Canonical name: `numpy.ushort` | :Alias on this platform (win32 AMD64): `numpy.uint16`: 16-bit unsigned integer (``0`` to ``65_535``). | | Method resolution order: | uint16 | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | uint16.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.uint16(127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.uint32
Python Library Documentation: class uint32 in module numpy class uint32(unsignedinteger) | Method resolution order: | uint32 | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | uint32.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.uint32(127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.uint64
Python Library Documentation: class uint64 in module numpy class uint64(unsignedinteger) | Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit | systems. | | :Character code: ``'Q'`` | :Canonical name: `numpy.uint` | :Alias on this platform (win32 AMD64): `numpy.uint64`: 64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``). | :Alias on this platform (win32 AMD64): `numpy.uintp`: Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``. | | Method resolution order: | uint64 | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | uint64.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.uint64(127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.uint8
Python Library Documentation: class uint8 in module numpy class uint8(unsignedinteger) | Unsigned integer type, compatible with C ``unsigned char``. | | :Character code: ``'B'`` | :Canonical name: `numpy.ubyte` | :Alias on this platform (win32 AMD64): `numpy.uint8`: 8-bit unsigned integer (``0`` to ``255``). | | Method resolution order: | uint8 | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | uint8.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.uint8(127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.uintc
Python Library Documentation: class uintc in module numpy class uintc(unsignedinteger) | Unsigned integer type, compatible with C ``unsigned int``. | | :Character code: ``'I'`` | | Method resolution order: | uintc | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.uintp
Python Library Documentation: class uint64 in module numpy class uint64(unsignedinteger) | Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit | systems. | | :Character code: ``'Q'`` | :Canonical name: `numpy.uint` | :Alias on this platform (win32 AMD64): `numpy.uint64`: 64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``). | :Alias on this platform (win32 AMD64): `numpy.uintp`: Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``. | | Method resolution order: | uint64 | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | uint64.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.uint64(127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.ulong
Python Library Documentation: class uint32 in module numpy class uint32(unsignedinteger) | Method resolution order: | uint32 | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | uint32.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.uint32(127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.ulonglong
Python Library Documentation: class uint64 in module numpy class uint64(unsignedinteger) | Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bit | systems. | | :Character code: ``'Q'`` | :Canonical name: `numpy.uint` | :Alias on this platform (win32 AMD64): `numpy.uint64`: 64-bit unsigned integer (``0`` to ``18_446_744_073_709_551_615``). | :Alias on this platform (win32 AMD64): `numpy.uintp`: Unsigned integer large enough to fit pointer, compatible with C ``uintptr_t``. | | Method resolution order: | uint64 | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | uint64.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.uint64(127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.union1d
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
union1d(ar1, ar2)
Find the union of two arrays.
Return the unique, sorted array of values that are in either of the two
input arrays.
Parameters
----------
ar1, ar2 : array_like
Input arrays. They are flattened if they are not already 1D.
Returns
-------
union1d : ndarray
Unique, sorted union of the input arrays.
Examples
--------
>>> import numpy as np
>>> np.union1d([-1, 0, 1], [-2, 0, 2])
array([-2, -1, 0, 1, 2])
To find the union of more than two arrays, use functools.reduce:
>>> from functools import reduce
>>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
array([1, 2, 3, 4, 6])
numpy.unique
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, *, equal_nan=True)
Find the unique elements of an array.
Returns the sorted unique elements of an array. There are three optional
outputs in addition to the unique elements:
* the indices of the input array that give the unique values
* the indices of the unique array that reconstruct the input array
* the number of times each unique value comes up in the input array
Parameters
----------
ar : array_like
Input array. Unless `axis` is specified, this will be flattened if it
is not already 1-D.
return_index : bool, optional
If True, also return the indices of `ar` (along the specified axis,
if provided, or in the flattened array) that result in the unique array.
return_inverse : bool, optional
If True, also return the indices of the unique array (for the specified
axis, if provided) that can be used to reconstruct `ar`.
return_counts : bool, optional
If True, also return the number of times each unique item appears
in `ar`.
axis : int or None, optional
The axis to operate on. If None, `ar` will be flattened. If an integer,
the subarrays indexed by the given axis will be flattened and treated
as the elements of a 1-D array with the dimension of the given axis,
see the notes for more details. Object arrays or structured arrays
that contain objects are not supported if the `axis` kwarg is used. The
default is None.
.. versionadded:: 1.13.0
equal_nan : bool, optional
If True, collapses multiple NaN values in the return array into one.
.. versionadded:: 1.24
Returns
-------
unique : ndarray
The sorted unique values.
unique_indices : ndarray, optional
The indices of the first occurrences of the unique values in the
original array. Only provided if `return_index` is True.
unique_inverse : ndarray, optional
The indices to reconstruct the original array from the
unique array. Only provided if `return_inverse` is True.
unique_counts : ndarray, optional
The number of times each of the unique values comes up in the
original array. Only provided if `return_counts` is True.
.. versionadded:: 1.9.0
See Also
--------
repeat : Repeat elements of an array.
Notes
-----
When an axis is specified the subarrays indexed by the axis are sorted.
This is done by making the specified axis the first dimension of the array
(move the axis to the first dimension to keep the order of the other axes)
and then flattening the subarrays in C order. The flattened subarrays are
then viewed as a structured type with each element given a label, with the
effect that we end up with a 1-D array of structured types that can be
treated in the same way as any other 1-D array. The result is that the
flattened subarrays are sorted in lexicographic order starting with the
first element.
.. versionchanged: 1.21
If nan values are in the input array, a single nan is put
to the end of the sorted unique values.
Also for complex arrays all NaN values are considered equivalent
(no matter whether the NaN is in the real or imaginary part).
As the representant for the returned array the smallest one in the
lexicographical order is chosen - see np.sort for how the lexicographical
order is defined for complex arrays.
.. versionchanged: 2.0
For multi-dimensional inputs, ``unique_inverse`` is reshaped
such that the input can be reconstructed using
``np.take(unique, unique_inverse, axis=axis)``. The result is
now not 1-dimensional when ``axis=None``.
Note that in NumPy 2.0.0 a higher dimensional array was returned also
when ``axis`` was not ``None``. This was reverted, but
``inverse.reshape(-1)`` can be used to ensure compatibility with both
versions.
Examples
--------
>>> import numpy as np
>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])
Return the unique rows of a 2D array
>>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
>>> np.unique(a, axis=0)
array([[1, 0, 0], [2, 3, 4]])
Return the indices of the original array that give the unique values:
>>> a = np.array(['a', 'b', 'b', 'c', 'a'])
>>> u, indices = np.unique(a, return_index=True)
>>> u
array(['a', 'b', 'c'], dtype='<U1')
>>> indices
array([0, 1, 3])
>>> a[indices]
array(['a', 'b', 'c'], dtype='<U1')
Reconstruct the input array from the unique values and inverse:
>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.unique(a, return_inverse=True)
>>> u
array([1, 2, 3, 4, 6])
>>> indices
array([0, 1, 4, 3, 1, 2, 1])
>>> u[indices]
array([1, 2, 6, 4, 2, 3, 2])
Reconstruct the input values from the unique values and counts:
>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> values, counts = np.unique(a, return_counts=True)
>>> values
array([1, 2, 3, 4, 6])
>>> counts
array([1, 3, 1, 1, 1])
>>> np.repeat(values, counts)
array([1, 2, 2, 2, 3, 4, 6]) # original order not preserved
numpy.unique_all
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
unique_all(x)
Find the unique elements of an array, and counts, inverse and indices.
This function is an Array API compatible alternative to:
>>> x = np.array([1, 1, 2])
>>> np.unique(x, return_index=True, return_inverse=True,
... return_counts=True, equal_nan=False)
(array([1, 2]), array([0, 2]), array([0, 0, 1]), array([2, 1]))
Parameters
----------
x : array_like
Input array. It will be flattened if it is not already 1-D.
Returns
-------
out : namedtuple
The result containing:
* values - The unique elements of an input array.
* indices - The first occurring indices for each unique element.
* inverse_indices - The indices from the set of unique elements
that reconstruct `x`.
* counts - The corresponding counts for each unique element.
See Also
--------
unique : Find the unique elements of an array.
Examples
--------
>>> import numpy as np
>>> np.unique_all([1, 1, 2])
UniqueAllResult(values=array([1, 2]),
indices=array([0, 2]),
inverse_indices=array([0, 0, 1]),
counts=array([2, 1]))
numpy.unique_counts
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
unique_counts(x)
Find the unique elements and counts of an input array `x`.
This function is an Array API compatible alternative to:
>>> x = np.array([1, 1, 2])
>>> np.unique(x, return_counts=True, equal_nan=False)
(array([1, 2]), array([2, 1]))
Parameters
----------
x : array_like
Input array. It will be flattened if it is not already 1-D.
Returns
-------
out : namedtuple
The result containing:
* values - The unique elements of an input array.
* counts - The corresponding counts for each unique element.
See Also
--------
unique : Find the unique elements of an array.
Examples
--------
>>> import numpy as np
>>> np.unique_counts([1, 1, 2])
UniqueCountsResult(values=array([1, 2]), counts=array([2, 1]))
numpy.unique_inverse
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
unique_inverse(x)
Find the unique elements of `x` and indices to reconstruct `x`.
This function is Array API compatible alternative to:
>>> x = np.array([1, 1, 2])
>>> np.unique(x, return_inverse=True, equal_nan=False)
(array([1, 2]), array([0, 0, 1]))
Parameters
----------
x : array_like
Input array. It will be flattened if it is not already 1-D.
Returns
-------
out : namedtuple
The result containing:
* values - The unique elements of an input array.
* inverse_indices - The indices from the set of unique elements
that reconstruct `x`.
See Also
--------
unique : Find the unique elements of an array.
Examples
--------
>>> import numpy as np
>>> np.unique_inverse([1, 1, 2])
UniqueInverseResult(values=array([1, 2]), inverse_indices=array([0, 0, 1]))
numpy.unique_values
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
unique_values(x)
Returns the unique elements of an input array `x`.
This function is Array API compatible alternative to:
>>> x = np.array([1, 1, 2])
>>> np.unique(x, equal_nan=False)
array([1, 2])
Parameters
----------
x : array_like
Input array. It will be flattened if it is not already 1-D.
Returns
-------
out : ndarray
The unique elements of an input array.
See Also
--------
unique : Find the unique elements of an array.
Examples
--------
>>> import numpy as np
>>> np.unique_values([1, 1, 2])
array([1, 2])
numpy.unpackbits
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
unpackbits(...)
unpackbits(a, /, axis=None, count=None, bitorder='big')
Unpacks elements of a uint8 array into a binary-valued output array.
Each element of `a` represents a bit-field that should be unpacked
into a binary-valued output array. The shape of the output array is
either 1-D (if `axis` is ``None``) or the same shape as the input
array with unpacking done along the axis specified.
Parameters
----------
a : ndarray, uint8 type
Input array.
axis : int, optional
The dimension over which bit-unpacking is done.
``None`` implies unpacking the flattened array.
count : int or None, optional
The number of elements to unpack along `axis`, provided as a way
of undoing the effect of packing a size that is not a multiple
of eight. A non-negative number means to only unpack `count`
bits. A negative number means to trim off that many bits from
the end. ``None`` means to unpack the entire array (the
default). Counts larger than the available number of bits will
add zero padding to the output. Negative counts must not
exceed the available number of bits.
.. versionadded:: 1.17.0
bitorder : {'big', 'little'}, optional
The order of the returned bits. 'big' will mimic bin(val),
``3 = 0b00000011 => [0, 0, 0, 0, 0, 0, 1, 1]``, 'little' will reverse
the order to ``[1, 1, 0, 0, 0, 0, 0, 0]``.
Defaults to 'big'.
.. versionadded:: 1.17.0
Returns
-------
unpacked : ndarray, uint8 type
The elements are binary-valued (0 or 1).
See Also
--------
packbits : Packs the elements of a binary-valued array into bits in
a uint8 array.
Examples
--------
>>> import numpy as np
>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
[ 7],
[23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)
>>> c = np.unpackbits(a, axis=1, count=-3)
>>> c
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1, 0]], dtype=uint8)
>>> p = np.packbits(b, axis=0)
>>> np.unpackbits(p, axis=0)
array([[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
>>> np.array_equal(b, np.unpackbits(p, axis=0, count=b.shape[0]))
True
numpy.unravel_index
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
unravel_index(...)
unravel_index(indices, shape, order='C')
Converts a flat index or array of flat indices into a tuple
of coordinate arrays.
Parameters
----------
indices : array_like
An integer array whose elements are indices into the flattened
version of an array of dimensions ``shape``. Before version 1.6.0,
this function accepted just one index value.
shape : tuple of ints
The shape of the array to use for unraveling ``indices``.
.. versionchanged:: 1.16.0
Renamed from ``dims`` to ``shape``.
order : {'C', 'F'}, optional
Determines whether the indices should be viewed as indexing in
row-major (C-style) or column-major (Fortran-style) order.
.. versionadded:: 1.6.0
Returns
-------
unraveled_coords : tuple of ndarray
Each array in the tuple has the same shape as the ``indices``
array.
See Also
--------
ravel_multi_index
Examples
--------
>>> import numpy as np
>>> np.unravel_index([22, 41, 37], (7,6))
(array([3, 6, 6]), array([4, 5, 1]))
>>> np.unravel_index([31, 41, 13], (7,6), order='F')
(array([3, 6, 6]), array([4, 5, 1]))
>>> np.unravel_index(1621, (6,7,8,9))
(3, 1, 4, 1)
numpy.unsignedinteger
Python Library Documentation: class unsignedinteger in module numpy class unsignedinteger(integer) | Abstract base class of all unsigned integer scalar types. | | Method resolution order: | unsignedinteger | integer | number | generic | builtins.object | | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Class methods inherited from number: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __copy__(...) | | __deepcopy__(...) | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __format__(...) | NumPy array scalar formatter | | __ge__(self, value, /) | Return self>=value. | | __getitem__(self, key, /) | Return self[key]. | | __gt__(self, value, /) | Return self>value. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __reduce__(...) | Helper for pickle. | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension. | | ---------------------------------------------------------------------- | Data and other attributes inherited from generic: | | __hash__ = None
numpy.unstack
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
unstack(x, /, *, axis=0)
Split an array into a sequence of arrays along the given axis.
The ``axis`` parameter specifies the dimension along which the array will
be split. For example, if ``axis=0`` (the default) it will be the first
dimension and if ``axis=-1`` it will be the last dimension.
The result is a tuple of arrays split along ``axis``.
.. versionadded:: 2.1.0
Parameters
----------
x : ndarray
The array to be unstacked.
axis : int, optional
Axis along which the array will be split. Default: ``0``.
Returns
-------
unstacked : tuple of ndarrays
The unstacked arrays.
See Also
--------
stack : Join a sequence of arrays along a new axis.
concatenate : Join a sequence of arrays along an existing axis.
block : Assemble an nd-array from nested lists of blocks.
split : Split array into a list of multiple sub-arrays of equal size.
Notes
-----
``unstack`` serves as the reverse operation of :py:func:`stack`, i.e.,
``stack(unstack(x, axis=axis), axis=axis) == x``.
This function is equivalent to ``tuple(np.moveaxis(x, axis, 0))``, since
iterating on an array iterates along the first axis.
Examples
--------
>>> arr = np.arange(24).reshape((2, 3, 4))
>>> np.unstack(arr)
(array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]]),
array([[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]))
>>> np.unstack(arr, axis=1)
(array([[ 0, 1, 2, 3],
[12, 13, 14, 15]]),
array([[ 4, 5, 6, 7],
[16, 17, 18, 19]]),
array([[ 8, 9, 10, 11],
[20, 21, 22, 23]]))
>>> arr2 = np.stack(np.unstack(arr, axis=1), axis=1)
>>> arr2.shape
(2, 3, 4)
>>> np.all(arr == arr2)
np.True_
numpy.unwrap
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
unwrap(p, discont=None, axis=-1, *, period=6.283185307179586)
Unwrap by taking the complement of large deltas with respect to the period.
This unwraps a signal `p` by changing elements which have an absolute
difference from their predecessor of more than ``max(discont, period/2)``
to their `period`-complementary values.
For the default case where `period` is :math:`2\pi` and `discont` is
:math:`\pi`, this unwraps a radian phase `p` such that adjacent differences
are never greater than :math:`\pi` by adding :math:`2k\pi` for some
integer :math:`k`.
Parameters
----------
p : array_like
Input array.
discont : float, optional
Maximum discontinuity between values, default is ``period/2``.
Values below ``period/2`` are treated as if they were ``period/2``.
To have an effect different from the default, `discont` should be
larger than ``period/2``.
axis : int, optional
Axis along which unwrap will operate, default is the last axis.
period : float, optional
Size of the range over which the input wraps. By default, it is
``2 pi``.
.. versionadded:: 1.21.0
Returns
-------
out : ndarray
Output array.
See Also
--------
rad2deg, deg2rad
Notes
-----
If the discontinuity in `p` is smaller than ``period/2``,
but larger than `discont`, no unwrapping is done because taking
the complement would only make the discontinuity larger.
Examples
--------
>>> import numpy as np
>>> phase = np.linspace(0, np.pi, num=5)
>>> phase[3:] += np.pi
>>> phase
array([ 0. , 0.78539816, 1.57079633, 5.49778714, 6.28318531]) # may vary
>>> np.unwrap(phase)
array([ 0. , 0.78539816, 1.57079633, -0.78539816, 0. ]) # may vary
>>> np.unwrap([0, 1, 2, -1, 0], period=4)
array([0, 1, 2, 3, 4])
>>> np.unwrap([ 1, 2, 3, 4, 5, 6, 1, 2, 3], period=6)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.unwrap([2, 3, 4, 5, 2, 3, 4, 5], period=4)
array([2, 3, 4, 5, 6, 7, 8, 9])
>>> phase_deg = np.mod(np.linspace(0 ,720, 19), 360) - 180
>>> np.unwrap(phase_deg, period=360)
array([-180., -140., -100., -60., -20., 20., 60., 100., 140.,
180., 220., 260., 300., 340., 380., 420., 460., 500.,
540.])
numpy.ushort
Python Library Documentation: class uint16 in module numpy class uint16(unsignedinteger) | Unsigned integer type, compatible with C ``unsigned short``. | | :Character code: ``'H'`` | :Canonical name: `numpy.ushort` | :Alias on this platform (win32 AMD64): `numpy.uint16`: 16-bit unsigned integer (``0`` to ``65_535``). | | Method resolution order: | uint16 | unsignedinteger | integer | number | generic | builtins.object | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | | __and__(self, value, /) | Return self&value. | | __bool__(self, /) | True if self else False | | __buffer__(self, flags, /) | Return a buffer object that exposes the underlying memory of the object. | | __divmod__(self, value, /) | Return divmod(self, value). | | __eq__(self, value, /) | Return self==value. | | __float__(self, /) | float(self) | | __floordiv__(self, value, /) | Return self//value. | | __ge__(self, value, /) | Return self>=value. | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __index__(self, /) | Return self converted to an integer, if self is suitable for use as an index into a list. | | __int__(self, /) | int(self) | | __invert__(self, /) | ~self | | __le__(self, value, /) | Return self<=value. | | __lshift__(self, value, /) | Return self<<value. | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __neg__(self, /) | -self | | __or__(self, value, /) | Return self|value. | | __pos__(self, /) | +self | | __pow__(self, value, mod=None, /) | Return pow(self, value, mod). | | __radd__(self, value, /) | Return value+self. | | __rand__(self, value, /) | Return value&self. | | __rdivmod__(self, value, /) | Return divmod(value, self). | | __repr__(self, /) | Return repr(self). | | __rfloordiv__(self, value, /) | Return value//self. | | __rlshift__(self, value, /) | Return value<<self. | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __ror__(self, value, /) | Return value|self. | | __rpow__(self, value, mod=None, /) | Return pow(value, self, mod). | | __rrshift__(self, value, /) | Return value>>self. | | __rshift__(self, value, /) | Return self>>value. | | __rsub__(self, value, /) | Return value-self. | | __rtruediv__(self, value, /) | Return value/self. | | __rxor__(self, value, /) | Return value^self. | | __str__(self, /) | Return str(self). | | __sub__(self, value, /) | Return self-value. | | __truediv__(self, value, /) | Return self/value. | | __xor__(self, value, /) | Return self^value. | | bit_count(...) | uint16.bit_count() -> int | | Computes the number of 1-bits in the absolute value of the input. | Analogous to the builtin `int.bit_count` or ``popcount`` in C++. | | Examples | -------- | >>> np.uint16(127).bit_count() | 7 | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | __class_getitem__(item, /) | | Return a parametrized wrapper around the `~numpy.number` type. | | .. versionadded:: 1.22 | | Returns | ------- | alias : types.GenericAlias | A parametrized `~numpy.number` type. | | Examples | -------- | >>> from typing import Any | >>> import numpy as np | | >>> np.signedinteger[Any] | numpy.signedinteger[typing.Any] | | See Also | -------- | :pep:`585` : Type hinting generics in standard collections. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from integer: | | __round__(...) | | is_integer(...) | integer.is_integer() -> bool | | Return ``True`` if the number is finite with integral value. | | .. versionadded:: 1.22 | | Examples | -------- | >>> import numpy as np | >>> np.int64(-2).is_integer() | True | >>> np.uint32(5).is_integer() | True | | ---------------------------------------------------------------------- | Data descriptors inherited from integer: | | denominator | denominator of value (1) | | numerator | numerator of value (the value itself) | | ---------------------------------------------------------------------- | Methods inherited from generic: | | __array__(...) | sc.__array__(dtype) return 0-dim array from scalar with specified dtype | | __array_namespace__(...) | | __array_wrap__(...) | sc.__array_wrap__(obj) return scalar from array | | __copy__(...) | | __deepcopy__(...) | | __format__(...) | NumPy array scalar formatter | | __getitem__(self, key, /) | Return self[key]. | | __reduce__(...) | Helper for pickle. | | __setstate__(...) | | __sizeof__(...) | Size of object in memory, in bytes. | | all(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.all`. | | any(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.any`. | | argmax(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmax`. | | argmin(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argmin`. | | argsort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.argsort`. | | astype(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.astype`. | | byteswap(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.byteswap`. | | choose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.choose`. | | clip(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.clip`. | | compress(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.compress`. | | conj(...) | | conjugate(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.conjugate`. | | copy(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.copy`. | | cumprod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumprod`. | | cumsum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.cumsum`. | | diagonal(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.diagonal`. | | dump(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dump`. | | dumps(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.dumps`. | | fill(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.fill`. | | flatten(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.flatten`. | | getfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.getfield`. | | item(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.item`. | | max(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.max`. | | mean(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.mean`. | | min(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.min`. | | nonzero(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.nonzero`. | | prod(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.prod`. | | put(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.put`. | | ravel(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.ravel`. | | repeat(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.repeat`. | | reshape(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.reshape`. | | resize(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.resize`. | | round(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.round`. | | searchsorted(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.searchsorted`. | | setfield(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setfield`. | | setflags(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.setflags`. | | sort(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sort`. | | squeeze(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.squeeze`. | | std(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.std`. | | sum(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.sum`. | | swapaxes(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.swapaxes`. | | take(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.take`. | | to_device(...) | | tobytes(...) | | tofile(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tofile`. | | tolist(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tolist`. | | tostring(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.tostring`. | | trace(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.trace`. | | transpose(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.transpose`. | | var(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.var`. | | view(...) | Scalar method identical to the corresponding array attribute. | | Please see `ndarray.view`. | | ---------------------------------------------------------------------- | Data descriptors inherited from generic: | | T | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.T`. | | __array_interface__ | Array protocol: Python side | | __array_priority__ | Array priority. | | __array_struct__ | Array protocol: struct | | base | Scalar attribute identical to the corresponding array attribute. | | Please see `ndarray.base`. | | data | Pointer to start of data. | | device | | dtype | Get array data-descriptor. | | flags | The integer value of flags. | | flat | A 1-D view of the scalar. | | imag | The imaginary part of the scalar. | | itemset | | itemsize | The length of one element in bytes. | | nbytes | | ndim | The number of array dimensions. | | newbyteorder | | ptp | | real | The real part of the scalar. | | shape | Tuple of array dimensions. | | size | The number of elements in the gentype. | | strides | Tuple of bytes steps in each dimension.
numpy.vander
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
vander(x, N=None, increasing=False)
Generate a Vandermonde matrix.
The columns of the output matrix are powers of the input vector. The
order of the powers is determined by the `increasing` boolean argument.
Specifically, when `increasing` is False, the `i`-th output column is
the input vector raised element-wise to the power of ``N - i - 1``. Such
a matrix with a geometric progression in each row is named for Alexandre-
Theophile Vandermonde.
Parameters
----------
x : array_like
1-D input array.
N : int, optional
Number of columns in the output. If `N` is not specified, a square
array is returned (``N = len(x)``).
increasing : bool, optional
Order of the powers of the columns. If True, the powers increase
from left to right, if False (the default) they are reversed.
.. versionadded:: 1.9.0
Returns
-------
out : ndarray
Vandermonde matrix. If `increasing` is False, the first column is
``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is
True, the columns are ``x^0, x^1, ..., x^(N-1)``.
See Also
--------
polynomial.polynomial.polyvander
Examples
--------
>>> import numpy as np
>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> np.column_stack([x**(N-1-i) for i in range(N)])
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> x = np.array([1, 2, 3, 5])
>>> np.vander(x)
array([[ 1, 1, 1, 1],
[ 8, 4, 2, 1],
[ 27, 9, 3, 1],
[125, 25, 5, 1]])
>>> np.vander(x, increasing=True)
array([[ 1, 1, 1, 1],
[ 1, 2, 4, 8],
[ 1, 3, 9, 27],
[ 1, 5, 25, 125]])
The determinant of a square Vandermonde matrix is the product
of the differences between the values of the input vector:
>>> np.linalg.det(np.vander(x))
48.000000000000043 # may vary
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48
numpy.var
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>, mean=<no value>, correction=<no value>)
Compute the variance along the specified axis.
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.
Parameters
----------
a : array_like
Array containing numbers whose variance is desired. If `a` is not an
array, a conversion is attempted.
axis : None or int or tuple of ints, optional
Axis or axes along which the variance is computed. The default is to
compute the variance of the flattened array.
.. versionadded:: 1.7.0
If this is a tuple of ints, a variance is performed over multiple axes,
instead of a single axis or all the axes as before.
dtype : data-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.
out : ndarray, 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.
ddof : {int, float}, optional
"Delta Degrees of Freedom": the divisor used in the calculation is
``N - ddof``, where ``N`` represents the number of elements. By
default `ddof` is zero. See notes for details about use of `ddof`.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.
If the default value is passed, then `keepdims` will not be
passed through to the `var` method of sub-classes of
`ndarray`, however any non-default value will be. If the
sub-class' method does not implement `keepdims` any
exceptions will be raised.
where : array_like of bool, optional
Elements to include in the variance. See `~numpy.ufunc.reduce` for
details.
.. versionadded:: 1.20.0
mean : array like, optional
Provide the mean to prevent its recalculation. The mean should have
a shape as if it was calculated with ``keepdims=True``.
The axis for the calculation of the mean should be the same as used in
the call to this var function.
.. versionadded:: 1.26.0
correction : {int, float}, optional
Array API compatible name for the ``ddof`` parameter. Only one of them
can be provided at the same time.
.. versionadded:: 2.0.0
Returns
-------
variance : ndarray, see dtype parameter above
If ``out=None``, returns a new array containing the variance;
otherwise, a reference to the output array is returned.
See Also
--------
std, mean, nanmean, nanstd, nanvar
:ref:`ufuncs-output-type`
Notes
-----
There are several common variants of the array variance calculation.
Assuming the input `a` is a one-dimensional NumPy array and ``mean`` is
either provided as an argument or computed as ``a.mean()``, NumPy
computes the variance of an array as::
N = len(a)
d2 = abs(a - mean)**2 # abs is for complex `a`
var = d2.sum() / (N - ddof) # note use of `ddof`
Different values of the argument `ddof` are useful in different
contexts. NumPy's default ``ddof=0`` corresponds with the expression:
.. math::
\frac{\sum_i{|a_i - \bar{a}|^2 }}{N}
which is sometimes called the "population variance" in the field of
statistics because it applies the definition of variance to `a` as if `a`
were a complete population of possible observations.
Many other libraries define the variance of an array differently, e.g.:
.. math::
\frac{\sum_i{|a_i - \bar{a}|^2}}{N - 1}
In statistics, the resulting quantity is sometimed called the "sample
variance" because if `a` is a random sample from a larger population,
this calculation provides an unbiased estimate of the variance of the
population. The use of :math:`N-1` in the denominator is often called
"Bessel's correction" because it corrects for bias (toward lower values)
in the variance estimate introduced when the sample mean of `a` is used
in place of the true mean of the population. For this quantity, use
``ddof=1``.
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.
Examples
--------
>>> import numpy as np
>>> a = np.array([[1, 2], [3, 4]])
>>> np.var(a)
1.25
>>> np.var(a, axis=0)
array([1., 1.])
>>> np.var(a, axis=1)
array([0.25, 0.25])
In single precision, var() can be inaccurate:
>>> a = np.zeros((2, 512*512), dtype=np.float32)
>>> a[0, :] = 1.0
>>> a[1, :] = 0.1
>>> np.var(a)
0.20250003
Computing the variance in float64 is more accurate:
>>> np.var(a, dtype=np.float64)
0.20249999932944759 # may vary
>>> ((1-0.55)**2 + (0.1-0.55)**2)/2
0.2025
Specifying a where argument:
>>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
>>> np.var(a)
6.833333333333333 # may vary
>>> np.var(a, where=[[True], [True], [False]])
4.0
Using the mean keyword to save computation time:
>>> import numpy as np
>>> from timeit import timeit
>>>
>>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
>>> mean = np.mean(a, axis=1, keepdims=True)
>>>
>>> g = globals()
>>> n = 10000
>>> t1 = timeit("var = np.var(a, axis=1, mean=mean)", globals=g, number=n)
>>> t2 = timeit("var = np.var(a, axis=1)", globals=g, number=n)
>>> print(f'Percentage execution time saved {100*(t2-t1)/t2:.0f}%')
#doctest: +SKIP
Percentage execution time saved 32%
numpy.vdot
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
vdot(...)
vdot(a, b, /)
Return the dot product of two vectors.
The vdot(`a`, `b`) function handles complex numbers differently than
dot(`a`, `b`). If the first argument is complex the complex conjugate
of the first argument is used for the calculation of the dot product.
Note that `vdot` handles multidimensional arrays differently than `dot`:
it does *not* perform a matrix product, but flattens input arguments
to 1-D vectors first. Consequently, it should only be used for vectors.
Parameters
----------
a : array_like
If `a` is complex the complex conjugate is taken before calculation
of the dot product.
b : array_like
Second argument to the dot product.
Returns
-------
output : ndarray
Dot product of `a` and `b`. Can be an int, float, or
complex depending on the types of `a` and `b`.
See Also
--------
dot : Return the dot product without using the complex conjugate of the
first argument.
Examples
--------
>>> import numpy as np
>>> a = np.array([1+2j,3+4j])
>>> b = np.array([5+6j,7+8j])
>>> np.vdot(a, b)
(70-8j)
>>> np.vdot(b, a)
(70+8j)
Note that higher-dimensional arrays are flattened!
>>> a = np.array([[1, 4], [5, 6]])
>>> b = np.array([[4, 1], [2, 2]])
>>> np.vdot(a, b)
30
>>> np.vdot(b, a)
30
>>> 1*4 + 4*1 + 5*2 + 6*2
30
numpy.vecdot
Python Library Documentation: ufunc
vecdot = <ufunc 'vecdot'>
vecdot(x1, x2, /, out=None, *, casting='same_kind', order='K', dtype=None, subok=True[, signature, axes, axis])
Vector dot product of two arrays.
Let :math:`\mathbf{a}` be a vector in `x1` and :math:`\mathbf{b}` be
a corresponding vector in `x2`. The dot product is defined as:
.. math::
\mathbf{a} \cdot \mathbf{b} = \sum_{i=0}^{n-1} \overline{a_i}b_i
where the sum is over the last dimension (unless `axis` is specified) and
where :math:`\overline{a_i}` denotes the complex conjugate if :math:`a_i`
is complex and the identity otherwise.
Parameters
----------
x1, x2 : array_like
Input arrays, scalars not allowed.
out : ndarray, optional
A location into which the result is stored. If provided, it must have
a shape that the broadcasted shape of `x1` and `x2` with the last axis
removed. If not provided or None, a freshly-allocated array is used.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
y : ndarray
The vector dot product of the inputs.
This is a scalar only when both x1, x2 are 1-d vectors.
Raises
------
ValueError
If the last dimension of `x1` is not the same size as
the last dimension of `x2`.
If a scalar value is passed in.
See Also
--------
vdot : same but flattens arguments first
einsum : Einstein summation convention.
Examples
--------
>>> import numpy as np
Get the projected size along a given normal for an array of vectors.
>>> v = np.array([[0., 5., 0.], [0., 0., 10.], [0., 6., 8.]])
>>> n = np.array([0., 0.6, 0.8])
>>> np.vecdot(v, n)
array([ 3., 8., 10.])
.. versionadded:: 2.0.0
numpy.vectorize
Python Library Documentation: class vectorize in module numpy class vectorize(builtins.object) | vectorize(pyfunc=<no value>, otypes=None, doc=None, excluded=None, cache=False, signature=None) | | vectorize(pyfunc=np._NoValue, otypes=None, doc=None, excluded=None, | cache=False, signature=None) | | Returns an object that acts like pyfunc, but takes arrays as input. | | Define a vectorized function which takes a nested sequence of objects or | numpy arrays as inputs and returns a single numpy array or a tuple of numpy | arrays. The vectorized function evaluates `pyfunc` over successive tuples | of the input arrays like the python map function, except it uses the | broadcasting rules of numpy. | | The data type of the output of `vectorized` is determined by calling | the function with the first element of the input. This can be avoided | by specifying the `otypes` argument. | | Parameters | ---------- | pyfunc : callable, optional | A python function or method. | Can be omitted to produce a decorator with keyword arguments. | otypes : str or list of dtypes, optional | The output data type. It must be specified as either a string of | typecode characters or a list of data type specifiers. There should | be one data type specifier for each output. | doc : str, optional | The docstring for the function. If None, the docstring will be the | ``pyfunc.__doc__``. | excluded : set, optional | Set of strings or integers representing the positional or keyword | arguments for which the function will not be vectorized. These will be | passed directly to `pyfunc` unmodified. | | .. versionadded:: 1.7.0 | | cache : bool, optional | If `True`, then cache the first function call that determines the number | of outputs if `otypes` is not provided. | | .. versionadded:: 1.7.0 | | signature : string, optional | Generalized universal function signature, e.g., ``(m,n),(n)->(m)`` for | vectorized matrix-vector multiplication. If provided, ``pyfunc`` will | be called with (and expected to return) arrays with shapes given by the | size of corresponding core dimensions. By default, ``pyfunc`` is | assumed to take scalars as input and output. | | .. versionadded:: 1.12.0 | | Returns | ------- | out : callable | A vectorized function if ``pyfunc`` was provided, | a decorator otherwise. | | See Also | -------- | frompyfunc : Takes an arbitrary Python function and returns a ufunc | | Notes | ----- | The `vectorize` function is provided primarily for convenience, not for | performance. The implementation is essentially a for loop. | | If `otypes` is not specified, then a call to the function with the | first argument will be used to determine the number of outputs. The | results of this call will be cached if `cache` is `True` to prevent | calling the function twice. However, to implement the cache, the | original function must be wrapped which will slow down subsequent | calls, so only do this if your function is expensive. | | The new keyword argument interface and `excluded` argument support | further degrades performance. | | References | ---------- | .. [1] :doc:`/reference/c-api/generalized-ufuncs` | | Examples | -------- | >>> import numpy as np | >>> def myfunc(a, b): | ... "Return a-b if a>b, otherwise return a+b" | ... if a > b: | ... return a - b | ... else: | ... return a + b | | >>> vfunc = np.vectorize(myfunc) | >>> vfunc([1, 2, 3, 4], 2) | array([3, 4, 1, 2]) | | The docstring is taken from the input function to `vectorize` unless it | is specified: | | >>> vfunc.__doc__ | 'Return a-b if a>b, otherwise return a+b' | >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`') | >>> vfunc.__doc__ | 'Vectorized `myfunc`' | | The output type is determined by evaluating the first element of the input, | unless it is specified: | | >>> out = vfunc([1, 2, 3, 4], 2) | >>> type(out[0]) | <class 'numpy.int64'> | >>> vfunc = np.vectorize(myfunc, otypes=[float]) | >>> out = vfunc([1, 2, 3, 4], 2) | >>> type(out[0]) | <class 'numpy.float64'> | | The `excluded` argument can be used to prevent vectorizing over certain | arguments. This can be useful for array-like arguments of a fixed length | such as the coefficients for a polynomial as in `polyval`: | | >>> def mypolyval(p, x): | ... _p = list(p) | ... res = _p.pop(0) | ... while _p: | ... res = res*x + _p.pop(0) | ... return res | >>> vpolyval = np.vectorize(mypolyval, excluded=['p']) | >>> vpolyval(p=[1, 2, 3], x=[0, 1]) | array([3, 6]) | | Positional arguments may also be excluded by specifying their position: | | >>> vpolyval.excluded.add(0) | >>> vpolyval([1, 2, 3], x=[0, 1]) | array([3, 6]) | | The `signature` argument allows for vectorizing functions that act on | non-scalar arrays of fixed length. For example, you can use it for a | vectorized calculation of Pearson correlation coefficient and its p-value: | | >>> import scipy.stats | >>> pearsonr = np.vectorize(scipy.stats.pearsonr, | ... signature='(n),(n)->(),()') | >>> pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]]) | (array([ 1., -1.]), array([ 0., 0.])) | | Or for a vectorized convolution: | | >>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)') | >>> convolve(np.eye(4), [1, 2, 1]) | array([[1., 2., 1., 0., 0., 0.], | [0., 1., 2., 1., 0., 0.], | [0., 0., 1., 2., 1., 0.], | [0., 0., 0., 1., 2., 1.]]) | | Decorator syntax is supported. The decorator can be called as | a function to provide keyword arguments: | | >>> @np.vectorize | ... def identity(x): | ... return x | ... | >>> identity([0, 1, 2]) | array([0, 1, 2]) | >>> @np.vectorize(otypes=[float]) | ... def as_float(x): | ... return x | ... | >>> as_float([0, 1, 2]) | array([0., 1., 2.]) | | Methods defined here: | | __call__(self, *args, **kwargs) from numpy.lib._function_base_impl.vectorize | Call self as a function. | | __init__(self, pyfunc=<no value>, otypes=None, doc=None, excluded=None, cache=False, signature=None) from numpy.lib._function_base_impl.vectorize | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object
numpy.void
Python Library Documentation: class void in module numpy
class void(flexible)
| np.void(length_or_data, /, dtype=None)
|
| Create a new structured or unstructured void scalar.
|
| Parameters
| ----------
| length_or_data : int, array-like, bytes-like, object
| One of multiple meanings (see notes). The length or
| bytes data of an unstructured void. Or alternatively,
| the data to be stored in the new scalar when `dtype`
| is provided.
| This can be an array-like, in which case an array may
| be returned.
| dtype : dtype, optional
| If provided the dtype of the new scalar. This dtype must
| be "void" dtype (i.e. a structured or unstructured void,
| see also :ref:`defining-structured-types`).
|
| .. versionadded:: 1.24
|
| Notes
| -----
| For historical reasons and because void scalars can represent both
| arbitrary byte data and structured dtypes, the void constructor
| has three calling conventions:
|
| 1. ``np.void(5)`` creates a ``dtype="V5"`` scalar filled with five
| ``\0`` bytes. The 5 can be a Python or NumPy integer.
| 2. ``np.void(b"bytes-like")`` creates a void scalar from the byte string.
| The dtype itemsize will match the byte string length, here ``"V10"``.
| 3. When a ``dtype=`` is passed the call is roughly the same as an
| array creation. However, a void scalar rather than array is returned.
|
| Please see the examples which show all three different conventions.
|
| Examples
| --------
| >>> np.void(5)
| np.void(b'\x00\x00\x00\x00\x00')
| >>> np.void(b'abcd')
| np.void(b'\x61\x62\x63\x64')
| >>> np.void((3.2, b'eggs'), dtype="d,S5")
| np.void((3.2, b'eggs'), dtype=[('f0', '<f8'), ('f1', 'S5')])
| >>> np.void(3, dtype=[('x', np.int8), ('y', np.int8)])
| np.void((3, 3), dtype=[('x', 'i1'), ('y', 'i1')])
|
| :Character code: ``'V'``
|
| Method resolution order:
| void
| flexible
| generic
| builtins.object
|
| Methods defined here:
|
| __buffer__(self, flags, /)
| Return a buffer object that exposes the underlying memory of the object.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __str__(self, /)
| Return str(self).
|
| getfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.getfield`.
|
| setfield(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setfield`.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| base
| base object
|
| dtype
| dtype object
|
| flags
| integer value of flags
|
| ----------------------------------------------------------------------
| Methods inherited from generic:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __array__(...)
| sc.__array__(dtype) return 0-dim array from scalar with specified dtype
|
| __array_namespace__(...)
|
| __array_wrap__(...)
| sc.__array_wrap__(obj) return scalar from array
|
| __bool__(self, /)
| True if self else False
|
| __copy__(...)
|
| __deepcopy__(...)
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __float__(self, /)
| float(self)
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(...)
| NumPy array scalar formatter
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __reduce__(...)
| Helper for pickle.
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __setstate__(...)
|
| __sizeof__(...)
| Size of object in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __xor__(self, value, /)
| Return self^value.
|
| all(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.all`.
|
| any(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.any`.
|
| argmax(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmax`.
|
| argmin(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argmin`.
|
| argsort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.argsort`.
|
| astype(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.astype`.
|
| byteswap(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.byteswap`.
|
| choose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.choose`.
|
| clip(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.clip`.
|
| compress(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.compress`.
|
| conj(...)
|
| conjugate(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.conjugate`.
|
| copy(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.copy`.
|
| cumprod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumprod`.
|
| cumsum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.cumsum`.
|
| diagonal(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.diagonal`.
|
| dump(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dump`.
|
| dumps(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.dumps`.
|
| fill(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.fill`.
|
| flatten(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.flatten`.
|
| item(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.item`.
|
| max(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.max`.
|
| mean(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.mean`.
|
| min(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.min`.
|
| nonzero(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.nonzero`.
|
| prod(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.prod`.
|
| put(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.put`.
|
| ravel(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.ravel`.
|
| repeat(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.repeat`.
|
| reshape(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.reshape`.
|
| resize(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.resize`.
|
| round(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.round`.
|
| searchsorted(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.searchsorted`.
|
| setflags(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.setflags`.
|
| sort(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sort`.
|
| squeeze(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.squeeze`.
|
| std(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.std`.
|
| sum(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.sum`.
|
| swapaxes(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.swapaxes`.
|
| take(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.take`.
|
| to_device(...)
|
| tobytes(...)
|
| tofile(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tofile`.
|
| tolist(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tolist`.
|
| tostring(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.tostring`.
|
| trace(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.trace`.
|
| transpose(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.transpose`.
|
| var(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.var`.
|
| view(...)
| Scalar method identical to the corresponding array attribute.
|
| Please see `ndarray.view`.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from generic:
|
| T
| Scalar attribute identical to the corresponding array attribute.
|
| Please see `ndarray.T`.
|
| __array_interface__
| Array protocol: Python side
|
| __array_priority__
| Array priority.
|
| __array_struct__
| Array protocol: struct
|
| data
| Pointer to start of data.
|
| device
|
| flat
| A 1-D view of the scalar.
|
| imag
| The imaginary part of the scalar.
|
| itemset
|
| itemsize
| The length of one element in bytes.
|
| nbytes
|
| ndim
| The number of array dimensions.
|
| newbyteorder
|
| ptp
|
| real
| The real part of the scalar.
|
| shape
| Tuple of array dimensions.
|
| size
| The number of elements in the gentype.
|
| strides
| Tuple of bytes steps in each dimension.
numpy.vsplit
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
vsplit(ary, indices_or_sections)
Split an array into multiple sub-arrays vertically (row-wise).
Please refer to the ``split`` documentation. ``vsplit`` is equivalent
to ``split`` with `axis=0` (default), the array is always split along the
first axis regardless of the array dimension.
See Also
--------
split : Split an array into multiple sub-arrays of equal size.
Examples
--------
>>> import numpy as np
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[12., 13., 14., 15.]])
>>> np.vsplit(x, 2)
[array([[0., 1., 2., 3.],
[4., 5., 6., 7.]]),
array([[ 8., 9., 10., 11.],
[12., 13., 14., 15.]])]
>>> np.vsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]]),
array([[12., 13., 14., 15.]]),
array([], shape=(0, 4), dtype=float64)]
With a higher dimensional array the split is still along the first axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[0., 1.],
[2., 3.]],
[[4., 5.],
[6., 7.]]])
>>> np.vsplit(x, 2)
[array([[[0., 1.],
[2., 3.]]]),
array([[[4., 5.],
[6., 7.]]])]
numpy.vstack
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
vstack(tup, *, dtype=None, casting='same_kind')
Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays
of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by
`vsplit`.
This function makes most sense for arrays with up to 3 dimensions. For
instance, for pixel-data with a height (first axis), width (second axis),
and r/g/b channels (third axis). The functions `concatenate`, `stack` and
`block` provide more general stacking and concatenation operations.
Parameters
----------
tup : sequence of ndarrays
The arrays must have the same shape along all but the first axis.
1-D arrays must have the same length.
dtype : str or dtype
If provided, the destination array will have this dtype. Cannot be
provided together with `out`.
.. versionadded:: 1.24
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur. Defaults to 'same_kind'.
.. versionadded:: 1.24
Returns
-------
stacked : ndarray
The array formed by stacking the given arrays, will be at least 2-D.
See Also
--------
concatenate : Join a sequence of arrays along an existing axis.
stack : Join a sequence of arrays along a new axis.
block : Assemble an nd-array from nested lists of blocks.
hstack : Stack arrays in sequence horizontally (column wise).
dstack : Stack arrays in sequence depth wise (along third axis).
column_stack : Stack 1-D arrays as columns into a 2-D array.
vsplit : Split an array into multiple sub-arrays vertically (row-wise).
unstack : Split an array into a tuple of sub-arrays along an axis.
Examples
--------
>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> b = np.array([4, 5, 6])
>>> np.vstack((a,b))
array([[1, 2, 3],
[4, 5, 6]])
>>> a = np.array([[1], [2], [3]])
>>> b = np.array([[4], [5], [6]])
>>> np.vstack((a,b))
array([[1],
[2],
[3],
[4],
[5],
[6]])
numpy.where
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
where(...)
where(condition, [x, y], /)
Return elements chosen from `x` or `y` depending on `condition`.
.. note::
When only `condition` is provided, this function is a shorthand for
``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
preferred, as it behaves correctly for subclasses. The rest of this
documentation covers only the case where all three arguments are
provided.
Parameters
----------
condition : array_like, bool
Where True, yield `x`, otherwise yield `y`.
x, y : array_like
Values from which to choose. `x`, `y` and `condition` need to be
broadcastable to some shape.
Returns
-------
out : ndarray
An array with elements from `x` where `condition` is True, and elements
from `y` elsewhere.
See Also
--------
choose
nonzero : The function that is called when x and y are omitted
Notes
-----
If all the arrays are 1-D, `where` is equivalent to::
[xv if c else yv
for c, xv, yv in zip(condition, x, y)]
Examples
--------
>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.where(a < 5, a, 10*a)
array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
This can be used on multidimensional arrays too:
>>> np.where([[True, False], [True, True]],
... [[1, 2], [3, 4]],
... [[9, 8], [7, 6]])
array([[1, 8],
[3, 4]])
The shapes of x, y, and the condition are broadcast together:
>>> x, y = np.ogrid[:3, :4]
>>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast
array([[10, 0, 0, 0],
[10, 11, 1, 1],
[10, 11, 12, 2]])
>>> a = np.array([[0, 1, 2],
... [0, 2, 4],
... [0, 3, 6]])
>>> np.where(a < 4, a, -1) # -1 is broadcast
array([[ 0, 1, 2],
[ 0, 2, -1],
[ 0, 3, -1]])
numpy.zeros
Python Library Documentation: built-in function zeros in module numpy
zeros(...)
zeros(shape, dtype=float, order='C', *, like=None)
Return a new array of given shape and type, filled with zeros.
Parameters
----------
shape : int or tuple of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
The desired data-type for the array, e.g., `numpy.int8`. Default is
`numpy.float64`.
order : {'C', 'F'}, optional, default: 'C'
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
like : array_like, optional
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.
.. versionadded:: 1.20.0
Returns
-------
out : ndarray
Array of zeros with the given shape, dtype, and order.
See Also
--------
zeros_like : Return an array of zeros with shape and type of input.
empty : Return a new uninitialized array.
ones : Return a new array setting values to one.
full : Return a new array of given shape filled with value.
Examples
--------
>>> import numpy as np
>>> np.zeros(5)
array([ 0., 0., 0., 0., 0.])
>>> np.zeros((5,), dtype=int)
array([0, 0, 0, 0, 0])
>>> np.zeros((2, 1))
array([[ 0.],
[ 0.]])
>>> s = (2,2)
>>> np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])
>>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
array([(0, 0), (0, 0)],
dtype=[('x', '<i4'), ('y', '<i4')])
numpy.zeros_like
Python Library Documentation: _ArrayFunctionDispatcher in module numpy
zeros_like(a, dtype=None, order='K', subok=True, shape=None, *, device=None)
Return an array of zeros with the same shape and type as a given array.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of
the returned array.
dtype : data-type, optional
Overrides the data type of the result.
.. versionadded:: 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.
.. versionadded:: 1.6.0
subok : bool, 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.
shape : int 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.
.. versionadded:: 1.17.0
device : str, optional
The device on which to place the created array. Default: None.
For Array-API interoperability only, so must be ``"cpu"`` if passed.
.. versionadded:: 2.0.0
Returns
-------
out : ndarray
Array of zeros with the same shape and type as `a`.
See Also
--------
empty_like : Return an empty array with shape and type of input.
ones_like : Return an array of ones with shape and type of input.
full_like : Return a new array with shape of input filled with value.
zeros : Return a new array setting values to zero.
Examples
--------
>>> import numpy as np
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.zeros_like(x)
array([[0, 0, 0],
[0, 0, 0]])
>>> y = np.arange(3, dtype=float)
>>> y
array([0., 1., 2.])
>>> np.zeros_like(y)
array([0., 0., 0.])