๐ฆ Help on package numpy:
๐ numpy
NumPy
Provides
Documentation is available in two forms: docstrings provided with the code, and a loose standing reference guide, available from the NumPy homepage.
We recommend exploring the docstrings using IPython, an advanced Python shell with TAB-completion and introspection capabilities. See below for further instructions.
The docstring examples assume that numpy has been imported as np:
>>> import numpy as np
Code snippets are indicated by three greater-than signs:
>>> x = 42
>>> x = x + 1
Use the built-in help function to view a function's docstring:
>>> help(np.sort)
... # doctest: +SKIP
For some objects, np.info(obj) may provide additional help. This is particularly true if you see the line "Help on ufunc object:" at the top of the help() page. Ufuncs are implemented in C, not Python, for speed. The native Python help() does not know how to view their help, but our np.info() function does.
To search for documents containing a keyword, do:
>>> np.lookfor('keyword')
... # doctest: +SKIP
General-purpose documents like a glossary and help on the basic concepts of numpy are available under the doc sub-module:
>>> from numpy import doc
>>> help(doc)
... # doctest: +SKIP
doc โ Topical documentation on broadcasting, indexing, etc.lib โ Basic functions used by several sub-packages.random โ Core Random Toolslinalg โ Core Linear Algebra Toolsfft โ Core FFT routinespolynomial โ Polynomial toolstesting โ NumPy testing toolsf2py โ Fortran to Python Interface Generator.distutils โ Enhancements to distutils with support for Fortran compilers support and more.test โ Run numpy unittestsshow_config โ Show numpy build configurationdual โ Overwrite certain functions with high-performance SciPy tools. Note: numpy.dual is deprecated. Use the functions from NumPy or Scipy directly instead of importing them from numpy.dual.matlib โ Make everything matrices.__version__ โ NumPy version stringStart IPython with the NumPy profile (ipython -p numpy), which will import numpy under the alias np. Then, use the cpaste command to paste examples into the shell. To see which functions are available in numpy, type np.<TAB> (where <TAB> refers to the TAB key), or use np.*cos*?<ENTER> (where <ENTER> refers to the ENTER key) to narrow down the list. To view the docstring for a function, use np.cos?<ENTER> (to view the docstring) and np.cos??<ENTER> (to view the source code).
Most of the functions in numpy return a copy of the array argument (e.g., np.sort). In-place versions of these functions are often available as array methods, i.e. x = np.array([1,2,3]); x.sort(). Exceptions to this rule are documented.
_matcharemathrec๐ Class hierarchy:
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.UserWarning(builtins.Warning)
RankWarning
VisibleDeprecationWarning
builtins.ValueError(builtins.Exception)
AxisError(builtins.ValueError, builtins.IndexError)
builtins.bytes(builtins.object)
bytes_(builtins.bytes, character)
builtins.object
DataSource
MachAr
broadcast
busdaycalendar
dtype
finfo
flatiter
format_parser
generic
bool_
datetime64
flexible
character
bytes_(builtins.bytes, character)
str_(builtins.str, character)
void
record
number
inexact
complexfloating
complex128(complexfloating, builtins.complex)
complex256
complex64
floating
float128
float16
float32
float64(floating, builtins.float)
integer
signedinteger
int16
int32
int64
int8
longlong
timedelta64
unsignedinteger
uint16
uint32
uint64
uint8
ulonglong
object_
iinfo
ndarray
chararray
matrix
memmap
recarray
ndenumerate
ndindex
nditer
poly1d
ufunc
vectorize
builtins.str(builtins.object)
str_(builtins.str, character)
contextlib.ContextDecorator(builtins.object)
errstate
Raised when an axis supplied is invalid.
AxisError(axis, ndim=None, msg_prefix=None) โ ๐ง Initialize self.Data descriptors:
__weakref__ โ list of weak referencesInherited from builtins.ValueError:
__new__ โ Create and return a new object.Inherited from builtins.BaseException:
__delattr__, __getattribute__, __reduce__, __repr__, __setattr__, __setstate__, __str__, with_traceback__cause__, __context__, __dict__, __suppress_context__, __traceback__, argsWarning raised when casting a complex dtype to a real dtype.
Inherited from builtins.RuntimeWarning:
__init__, __new__Inherited from builtins.BaseException: (same as above)
__delattr__ โฆ with_traceback__cause__, __context__, __dict__, __suppress_context__, __traceback__, argsGeneric data source file (file, http, ftp, โฆ).
__init__(self, destpath='.') โ Create a DataSource.abspath(self, path) โ ๐ Return absolute path of file.exists(self, path) โ ๐ Test if path exists.open(self, path, mode='r', encoding=None, newline=None) โ ๐ Open and return file-like object.Data descriptors:
__dict__, __weakref__Diagnosing machine parameters for floating point numbers.
__init__(self, float_conv=..., int_conv=..., float_to_float=..., float_to_str=..., title='...') โ ๐ Initialize.__str__(self) โ Return str(self).Data descriptors:
__dict__, __weakref__Attributes: ibeta, it, machep, eps, negep, epsneg, iexp, minexp, xmin, maxexp, xmax, irnd, ngrd, epsilon, tiny, huge, precision, resolution.
Special deprecation warning that does not cause test failures in nose.
Inherited from builtins.DeprecationWarning:
__init__, __new__Inherited from builtins.BaseException: (same as above)
Issued by polyfit when the Vandermonde matrix is rank deficient.
Inherited from builtins.UserWarning:
__init__, __new__Inherited from builtins.BaseException: (same as above)
Runtime error.
Inherited from builtins.RuntimeError:
__init__, __new__Inherited from builtins.BaseException: (same as above)
Visible deprecation warning for user bugs.
Inherited from builtins.UserWarning:
__init__, __new__Inherited from builtins.BaseException: (same as above)
Boolean type stored as a byte. Character code: '?'
__and__, __bool__, __eq__, __ge__, __gt__, __hash__, __index__, __le__, __lt__, __ne__, __or__, __rand__, __repr__, __ror__, __rxor__, __str__, __xor__, __new__Inherited from generic: Many methods for arithmetic, array operations, scalar attributes (see full list in original).
__abs__, __add__, __array__, __array_wrap__, __copy__, __deepcopy__, __divmod__, __float__, __floordiv__, __format__, __getitem__, __int__, __invert__, __lshift__, __mod__, __mul__, __neg__, __pos__, __pow__, __radd__, __rdivmod__, __reduce__, __rfloordiv__, __rlshift__, __rmod__, __rmul__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __setstate__, __sizeof__, __sub__, __truediv__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, viewData descriptors inherited from generic:
T, __array_interface__, __array_priority__, __array_struct__, base, data, dtype, flags, flat, imag, itemsize, nbytes, ndim, real, shape, size, stridesProduce an object that mimics broadcasting.
__iter__, __next__reset() โ ๐ Reset the broadcasted result's iterator(s).Data descriptors:
index โ current index in broadcasted resultiters โ tuple of iterators along componentsnd โ number of dimensionsndim โ alias for ndnumiter โ number of iteratorsshape โ shape of resultsize โ total sizeBusiness day calendar object for the busday family of functions.
__init__, __new__Data descriptors:
holidays โ copy of holiday arrayweekmask โ copy of seven-element boolean maskSigned integer type, compatible with C char. Character code: 'b'
__abs__, __add__, __and__, __bool__, __divmod__, __eq__, __float__, __floordiv__, __ge__, __gt__, __hash__, __index__, __int__, __invert__, __le__, __lshift__, __lt__, __mod__, __mul__, __ne__, __neg__, __or__, __pos__, __pow__, __radd__, __rand__, __rdivmod__, __repr__, __rfloordiv__, __rlshift__, __rmod__, __rmul__, __ror__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __str__, __sub__, __truediv__, __xor__, __new__Inherited from integer: __round__, denominator, numerator.
Inherited from generic: (same as bool_ above)
Byte string type, strips trailing null bytes in arrays. Character code: 'S'
__eq__, __ge__, __gt__, __hash__, __le__, __lt__, __ne__, __repr__, __str__, __new__Inherited from builtins.bytes: All standard bytes methods (capitalize, center, count, decode, endswith, expandtabs, find, hex, index, isalnum, isalpha, isascii, isdigit, islower, isspace, istitle, isupper, join, ljust, lower, lstrip, partition, removeprefix, removesuffix, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill, fromhex, maketrans)
Inherited from generic: (same as above)
All integer scalar types share the same methods and attributes as int8. They differ in range and character code. See int8 for complete method list.
Floating-point and complex scalar types. They inherit from floating or complexfloating. Methods include arithmetic operations, __float__, __int__, and all generic methods. Data descriptors include real, imag, etc.
String type. Character code 'U'. Similar to bytes_ but for Unicode strings. Inherits from builtins.str and character.
Base class for all NumPy scalar types. Provides the core methods and descriptors listed above for bool_.
Subclasses of generic for structured and character types.
Intermediate abstract base classes for numeric types.
Scalar type for Python objects.
Date and time scalar types.
Additional NumPy classes not detailed here. See full documentation for details.
bytes(iterable_of_ints) โ bytes
bytes(string, encoding[, errors]) โ bytes
bytes(bytes_or_buffer) โ immutable copy of bytes_or_buffer
bytes(int) โ bytes object of size given by the parameter initialized with null bytes
bytes() โ empty bytes object
Construct an immutable array of bytes.
__add__(self, value, /) โ Return self+value.__contains__(self, key, /) โ Return 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.__mod__(self, value, /) โ Return self%value.__mul__(self, value, /) โ Return self*value.__ne__(self, value, /) โ Return self!=value.__repr__(self, /) โ Return repr(self).__rmod__(self, value, /) โ Return value%self.__rmul__(self, value, /) โ Return value*self.__str__(self, /) โ Return str(self).capitalize(self, /) โ Return a capitalized version of the sequence.center(self, width, fillchar=b' ', /) โ Return a centered sequence of length width.count(self, sub, start=0, end=sys.maxsize, /) โ Return the number of non-overlapping occurrences of sub.decode(self, /, encoding='utf-8', errors='strict') โ Decode the bytes using the codec registered for encoding.endswith(self, suffix, start=0, end=sys.maxsize, /) โ Return True if self ends with suffix.expandtabs(self, /, tabsize=8) โ Return a copy with all tab characters replaced by spaces.find(self, sub, start=0, end=sys.maxsize, /) โ Return the lowest index in the sequence where sub is found.hex(self, /, sep='', bytes_per_sep=0) โ Return a string of hexadecimal digits.index(self, sub, start=0, end=sys.maxsize, /) โ Like find but raises ValueError when sub is not found.isalnum(self, /) โ Return True if all characters in the sequence are alphanumeric.isalpha(self, /) โ Return True if all characters in the sequence are alphabetic.isascii(self, /) โ Return True if all bytes in the sequence are ASCII.isdigit(self, /) โ Return True if all characters in the sequence are digits.islower(self, /) โ Return True if all cased characters are lowercase.isspace(self, /) โ Return True if all characters are whitespace.istitle(self, /) โ Return True if the sequence is titlecased.isupper(self, /) โ Return True if all cased characters are uppercase.join(self, iterable_of_bytes, /) โ Concatenate any number of bytes objects.ljust(self, width, fillchar=b' ', /) โ Return a left-justified sequence of length width.lower(self, /) โ Return a copy of the sequence with each uppercase character converted to lowercase.lstrip(self, chars=None, /) โ Return a copy with leading whitespace removed.maketrans(frm, to, /) โ Return a translation table for translate.partition(self, sep, /) โ Partition the sequence at the first occurrence of sep.removeprefix(self, prefix, /) โ Return a copy with the given prefix removed if present.removesuffix(self, suffix, /) โ Return a copy with the given suffix removed if present.replace(self, old, new, count=-1, /) โ Return a copy with occurrences of old replaced by new.rfind(self, sub, start=0, end=sys.maxsize, /) โ Return the highest index where sub is found.rindex(self, sub, start=0, end=sys.maxsize, /) โ Like rfind but raises ValueError.rjust(self, width, fillchar=b' ', /) โ Return a right-justified sequence of length width.rpartition(self, sep, /) โ Partition the sequence at the last occurrence of sep.rsplit(self, sep=None, maxsplit=-1, /) โ Return a list of the sequences in the sequence using sep as delimiter.rstrip(self, chars=None, /) โ Return a copy with trailing whitespace removed.split(self, sep=None, maxsplit=-1, /) โ Return a list of the sequences in the sequence using sep as delimiter.splitlines(self, keepends=False, /) โ Return a list of the lines in the sequence.startswith(self, prefix, start=0, end=sys.maxsize, /) โ Return True if self starts with prefix.strip(self, chars=None, /) โ Return a copy with leading and trailing whitespace removed.swapcase(self, /) โ Return a copy with uppercase characters converted to lowercase and vice versa.title(self, /) โ Return a titlecased version of the sequence.translate(self, table, /, delete=b'') โ Return a copy with each character mapped by the given translation table.upper(self, /) โ Return a copy of the sequence with all ASCII characters converted to uppercase.zfill(self, width, /) โ Pad a numeric string with zeros on the left.fromhex(string, /) โ Create a bytes object from a string of hexadecimal numbers.maketrans(frm, to, /) โ Return a translation table useable for the bytes or bytearray translate method.__abs__(self, /) โ abs(self)__and__(self, value, /) โ Return self&value.__array__(...) โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__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.any(...) โ Scalar method identical to the corresponding array attribute.argmax(...) โ Scalar method identical to the corresponding array attribute.argmin(...) โ Scalar method identical to the corresponding array attribute.argsort(...) โ Scalar method identical to the corresponding array attribute.astype(...) โ Scalar method identical to the corresponding array attribute.byteswap(...) โ Scalar method identical to the corresponding array attribute.choose(...) โ Scalar method identical to the corresponding array attribute.clip(...) โ Scalar method identical to the corresponding array attribute.compress(...) โ Scalar method identical to the corresponding array attribute.conj(...)conjugate(...) โ Scalar method identical to the corresponding array attribute.copy(...) โ Scalar method identical to the corresponding array attribute.cumprod(...) โ Scalar method identical to the corresponding array attribute.cumsum(...) โ Scalar method identical to the corresponding array attribute.diagonal(...) โ Scalar method identical to the corresponding array attribute.dump(...) โ Scalar method identical to the corresponding array attribute.dumps(...) โ Scalar method identical to the corresponding array attribute.fill(...) โ Scalar method identical to the corresponding array attribute.flatten(...) โ Scalar method identical to the corresponding array attribute.getfield(...) โ Scalar method identical to the corresponding array attribute.item(...) โ Scalar method identical to the corresponding array attribute.itemset(...) โ Scalar method identical to the corresponding array attribute.max(...) โ Scalar method identical to the corresponding array attribute.mean(...) โ Scalar method identical to the corresponding array attribute.min(...) โ Scalar method identical to the corresponding array attribute.newbyteorder(...) โ Return a new dtype with a different byte order.nonzero(...) โ Scalar method identical to the corresponding array attribute.prod(...) โ Scalar method identical to the corresponding array attribute.ptp(...) โ Scalar method identical to the corresponding array attribute.put(...) โ Scalar method identical to the corresponding array attribute.ravel(...) โ Scalar method identical to the corresponding array attribute.repeat(...) โ Scalar method identical to the corresponding array attribute.reshape(...) โ Scalar method identical to the corresponding array attribute.resize(...) โ Scalar method identical to the corresponding array attribute.round(...) โ Scalar method identical to the corresponding array attribute.searchsorted(...) โ Scalar method identical to the corresponding array attribute.setfield(...) โ Scalar method identical to the corresponding array attribute.setflags(...) โ Scalar method identical to the corresponding array attribute.sort(...) โ Scalar method identical to the corresponding array attribute.squeeze(...) โ Scalar method identical to the corresponding array attribute.std(...) โ Scalar method identical to the corresponding array attribute.sum(...) โ Scalar method identical to the corresponding array attribute.swapaxes(...) โ Scalar method identical to the corresponding array attribute.take(...) โ Scalar method identical to the corresponding array attribute.tobytes(...)tofile(...) โ Scalar method identical to the corresponding array attribute.tolist(...) โ Scalar method identical to the corresponding array attribute.tostring(...) โ Scalar method identical to the corresponding array attribute.trace(...) โ Scalar method identical to the corresponding array attribute.transpose(...) โ Scalar method identical to the corresponding array attribute.var(...) โ Scalar method identical to the corresponding array attribute.view(...) โ Scalar method identical to the corresponding array attribute.T โ Scalar attribute identical to the corresponding array attribute.__array_interface__ โ Array protocol: Python side__array_priority__ โ Array priority.__array_struct__ โ Array protocol: structbase โ Scalar attribute identical to the corresponding array attribute.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.cdouble(real=0, imag=0)
Complex number type composed of two double-precision floating-point numbers, compatible with Python complex.
'D'numpy.cdoublenumpy.cfloatnumpy.complex_numpy.complex128: Complex number type composed of 2 64-bit-precision floating-point numbers.Method resolution order:
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__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.__repr__(self, /) โ Return repr(self).__rfloordiv__(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.__new__(*args, **kwargs) โ Create and return a new object.__round__(...)__and__(self, value, /) โ Return self&value.__array__(...) โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__array_wrap__(...) โ sc.__array_wrap__(obj) return scalar from array__copy__(...)__deepcopy__(...)__divmod__(self, value, /) โ Return divmod(self, value).__format__(...) โ NumPy array scalar formatter__getitem__(self, key, /) โ Return self[key].__invert__(self, /) โ ~self__lshift__(self, value, /) โ Return self<<value.__mod__(self, value, /) โ Return self%value.__or__(self, value, /) โ Return self|value.__rand__(self, value, /) โ Return value&self.__rdivmod__(self, value, /) โ Return divmod(value, self).__reduce__(...) โ Helper for pickle.__rlshift__(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.__setstate__(...)__sizeof__(...) โ Size of object in memory, in bytes.__xor__(self, value, /) โ Return self^value.all(...) โ Scalar method identical to the corresponding array attribute.any(...) โ Scalar method identical to the corresponding array attribute.argmax(...) โ Scalar method identical to the corresponding array attribute.argmin(...) โ Scalar method identical to the corresponding array attribute.argsort(...) โ Scalar method identical to the corresponding array attribute.astype(...) โ Scalar method identical to the corresponding array attribute.byteswap(...) โ Scalar method identical to the corresponding array attribute.choose(...) โ Scalar method identical to the corresponding array attribute.clip(...) โ Scalar method identical to the corresponding array attribute.compress(...) โ Scalar method identical to the corresponding array attribute.conj(...)conjugate(...) โ Scalar method identical to the corresponding array attribute.copy(...) โ Scalar method identical to the corresponding array attribute.cumprod(...) โ Scalar method identical to the corresponding array attribute.cumsum(...) โ Scalar method identical to the corresponding array attribute.diagonal(...) โ Scalar method identical to the corresponding array attribute.dump(...) โ Scalar method identical to the corresponding array attribute.dumps(...) โ Scalar method identical to the corresponding array attribute.fill(...) โ Scalar method identical to the corresponding array attribute.flatten(...) โ Scalar method identical to the corresponding array attribute.getfield(...) โ Scalar method identical to the corresponding array attribute.item(...) โ Scalar method identical to the corresponding array attribute.itemset(...) โ Scalar method identical to the corresponding array attribute.max(...) โ Scalar method identical to the corresponding array attribute.mean(...) โ Scalar method identical to the corresponding array attribute.min(...) โ Scalar method identical to the corresponding array attribute.newbyteorder(...) โ Return a new dtype with a different byte order.nonzero(...) โ Scalar method identical to the corresponding array attribute.prod(...) โ Scalar method identical to the corresponding array attribute.ptp(...) โ Scalar method identical to the corresponding array attribute.put(...) โ Scalar method identical to the corresponding array attribute.ravel(...) โ Scalar method identical to the corresponding array attribute.repeat(...) โ Scalar method identical to the corresponding array attribute.reshape(...) โ Scalar method identical to the corresponding array attribute.resize(...) โ Scalar method identical to the corresponding array attribute.round(...) โ Scalar method identical to the corresponding array attribute.searchsorted(...) โ Scalar method identical to the corresponding array attribute.setfield(...) โ Scalar method identical to the corresponding array attribute.setflags(...) โ Scalar method identical to the corresponding array attribute.sort(...) โ Scalar method identical to the corresponding array attribute.squeeze(...) โ Scalar method identical to the corresponding array attribute.std(...) โ Scalar method identical to the corresponding array attribute.sum(...) โ Scalar method identical to the corresponding array attribute.swapaxes(...) โ Scalar method identical to the corresponding array attribute.take(...) โ Scalar method identical to the corresponding array attribute.tobytes(...)tofile(...) โ Scalar method identical to the corresponding array attribute.tolist(...) โ Scalar method identical to the corresponding array attribute.tostring(...) โ Scalar method identical to the corresponding array attribute.trace(...) โ Scalar method identical to the corresponding array attribute.transpose(...) โ Scalar method identical to the corresponding array attribute.var(...) โ Scalar method identical to the corresponding array attribute.view(...) โ Scalar method identical to the corresponding array attribute.T โ Scalar attribute identical to the corresponding array attribute.__array_interface__ โ Array protocol: Python side__array_priority__ โ Array priority.__array_struct__ โ Array protocol: structbase โ Scalar attribute identical to the corresponding array attribute.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.__getattribute__(self, name, /) โ Return getattr(self, name).__getnewargs__(self, /)Identical to cdouble (complex128) above. See the cdouble class documentation for all details.
Abstract base class of all character string scalar types.
Method resolution order:
__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_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).__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.any(...) โ Scalar method identical to the corresponding array attribute.argmax(...) โ Scalar method identical to the corresponding array attribute.argmin(...) โ Scalar method identical to the corresponding array attribute.argsort(...) โ Scalar method identical to the corresponding array attribute.astype(...) โ Scalar method identical to the corresponding array attribute.byteswap(...) โ Scalar method identical to the corresponding array attribute.choose(...) โ Scalar method identical to the corresponding array attribute.clip(...) โ Scalar method identical to the corresponding array attribute.compress(...) โ Scalar method identical to the corresponding array attribute.conj(...)conjugate(...) โ Scalar method identical to the corresponding array attribute.copy(...) โ Scalar method identical to the corresponding array attribute.cumprod(...) โ Scalar method identical to the corresponding array attribute.cumsum(...) โ Scalar method identical to the corresponding array attribute.diagonal(...) โ Scalar method identical to the corresponding array attribute.dump(...) โ Scalar method identical to the corresponding array attribute.dumps(...) โ Scalar method identical to the corresponding array attribute.fill(...) โ Scalar method identical to the corresponding array attribute.flatten(...) โ Scalar method identical to the corresponding array attribute.getfield(...) โ Scalar method identical to the corresponding array attribute.item(...) โ Scalar method identical to the corresponding array attribute.itemset(...) โ Scalar method identical to the corresponding array attribute.max(...) โ Scalar method identical to the corresponding array attribute.mean(...) โ Scalar method identical to the corresponding array attribute.min(...) โ Scalar method identical to the corresponding array attribute.newbyteorder(...) โ Return a new dtype with a different byte order.nonzero(...) โ Scalar method identical to the corresponding array attribute.prod(...) โ Scalar method identical to the corresponding array attribute.ptp(...) โ Scalar method identical to the corresponding array attribute.put(...) โ Scalar method identical to the corresponding array attribute.ravel(...) โ Scalar method identical to the corresponding array attribute.repeat(...) โ Scalar method identical to the corresponding array attribute.reshape(...) โ Scalar method identical to the corresponding array attribute.resize(...) โ Scalar method identical to the corresponding array attribute.round(...) โ Scalar method identical to the corresponding array attribute.searchsorted(...) โ Scalar method identical to the corresponding array attribute.setfield(...) โ Scalar method identical to the corresponding array attribute.setflags(...) โ Scalar method identical to the corresponding array attribute.sort(...) โ Scalar method identical to the corresponding array attribute.squeeze(...) โ Scalar method identical to the corresponding array attribute.std(...) โ Scalar method identical to the corresponding array attribute.sum(...) โ Scalar method identical to the corresponding array attribute.swapaxes(...) โ Scalar method identical to the corresponding array attribute.take(...) โ Scalar method identical to the corresponding array attribute.tobytes(...)tofile(...) โ Scalar method identical to the corresponding array attribute.tolist(...) โ Scalar method identical to the corresponding array attribute.tostring(...) โ Scalar method identical to the corresponding array attribute.trace(...) โ Scalar method identical to the corresponding array attribute.transpose(...) โ Scalar method identical to the corresponding array attribute.var(...) โ Scalar method identical to the corresponding array attribute.view(...) โ Scalar method identical to the corresponding array attribute.T โ Scalar attribute identical to the corresponding array attribute.__array_interface__ โ Array protocol: Python side__array_priority__ โ Array priority.__array_struct__ โ Array protocol: structbase โ Scalar attribute identical to the corresponding array attribute.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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__ = Nonechararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order='C')
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 object_, string_ or unicode_, and use the free functions in the numpy.char module for fast vectorized string operations.
Versus a regular NumPy array of type str or unicode, this class adds the following functionality:
.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".
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 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.>>> charar = np.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.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:
__add__(self, other) โ Return (self + other), that is string concatenation, element-wise.__array_finalize__(self, obj) โ None.__eq__(self, other) โ Return (self == other) element-wise.__ge__(self, other) โ Return (self >= other) element-wise.__getitem__(self, obj) โ Return self[key].__gt__(self, other) โ Return (self > other) element-wise.__le__(self, other) โ Return (self <= other) element-wise.__lt__(self, other) โ Return (self < other) element-wise.__mod__(self, i) โ Return (self % i), that is pre-Python 2.6 string formatting (interpolation), element-wise.__mul__(self, i) โ Return (self * i), that is string multiple concatenation, element-wise.__ne__(self, other) โ Return (self != other) element-wise.__radd__(self, other) โ Return (other + self), that is string concatenation, element-wise.__rmod__(self, other) โ Return value%self.__rmul__(self, i) โ Return (self * i), that is string multiple concatenation, element-wise.argsort(self, axis=-1, kind=None, order=None) โ Returns the indices that would sort this array.capitalize(self) โ Return a copy of self with only the first character of each element capitalized.center(self, width, fillchar=' ') โ Return a copy of self with its elements centered in a string of length width.count(self, sub, start=0, end=None) โ Returns an array with the number of non-overlapping occurrences of substring sub.decode(self, encoding=None, errors=None) โ Calls str.decode element-wise.encode(self, encoding=None, errors=None) โ Calls str.encode element-wise.endswith(self, suffix, start=0, end=None) โ Returns a boolean array which is True where the string element ends with suffix.expandtabs(self, tabsize=8) โ Return a copy of each string element where all tab characters are replaced by one or more spaces.find(self, sub, start=0, end=None) โ For each element, return the lowest index in the string where substring sub is found.index(self, sub, start=0, end=None) โ Like find, but raises ValueError when the substring is not found.isalnum(self) โ Returns true for each element if all characters in the string are alphanumeric.isalpha(self) โ Returns true for each element if all characters in the string are alphabetic.isdecimal(self) โ For each element, return True if there are only decimal characters.isdigit(self) โ Returns true for each element if all characters are digits.islower(self) โ Returns true for each element if all cased characters are lowercase.isnumeric(self) โ For each element, return True if there are only numeric characters.isspace(self) โ Returns true for each element if there are only whitespace characters.istitle(self) โ Returns true for each element if the element is a titlecased string.isupper(self) โ Returns true for each element if all cased characters are uppercase.join(self, seq) โ Return a string which is the concatenation of the strings in the sequence seq.ljust(self, width, fillchar=' ') โ Return an array with the elements left-justified in a string of length width.lower(self) โ Return an array with the elements converted to lowercase.lstrip(self, chars=None) โ For each element, return a copy with the leading characters removed.partition(self, sep) โ Partition each element around sep.replace(self, old, new, count=None) โ For each element, return a copy with all occurrences of substring old replaced by new.rfind(self, sub, start=0, end=None) โ For each element, return the highest index where substring sub is found.rindex(self, sub, start=0, end=None) โ Like rfind but raises ValueError.rjust(self, width, fillchar=' ') โ Return an array with the elements right-justified in a string of length width.rpartition(self, sep) โ Partition each element around sep.rsplit(self, sep=None, maxsplit=None) โ For each element, return a list of the words using sep as delimiter.rstrip(self, chars=None) โ For each element, return a copy with the trailing characters removed.split(self, sep=None, maxsplit=None) โ For each element, return a list of the words using sep as delimiter.splitlines(self, keepends=None) โ For each element, return a list of the lines in the element.startswith(self, prefix, start=0, end=None) โ Returns a boolean array which is True where the string element starts with prefix.strip(self, chars=None) โ For each element, return a copy with the leading and trailing characters removed.swapcase(self) โ For each element, return a copy with uppercase characters converted to lowercase and vice versa.title(self) โ For each element, return a titlecased version of the string.translate(self, table, deletechars=None) โ For each element, return a copy with characters removed and mapped via translation table.upper(self) โ Return an array with the elements converted to uppercase.zfill(self, width) โ Return the numeric string left-filled with zeros in a string of length width.__new__(subtype, shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order='C') โ Create and return a new object.__dict__ โ dictionary for instance variables (if defined)Data and other attributes defined here:
__hash__ = None__abs__(self, /) โ abs(self)__and__(self, value, /) โ Return self&value.__array__(...) โ a.__array__([dtype], /) โ reference if type unchanged, copy otherwise.__array_function__(...)__array_prepare__(...) โ a.__array_prepare__(obj) โ Object of same type.__array_ufunc__(...)__array_wrap__(...) โ a.__array_wrap__(obj) โ Object of same type.__bool__(self, /) โ True if self else False__complex__(...)__contains__(self, key, /) โ Return key in self.__copy__(...) โ a.__copy__()__deepcopy__(...) โ a.__deepcopy__(memo, /) โ Deep copy of array.__delitem__(self, key, /) โ Delete self[key].__divmod__(self, value, /) โ Return divmod(self, value).__float__(self, /) โ float(self)__floordiv__(self, value, /) โ Return self//value.__format__(...) โ Default object formatter.__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.__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.__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)any(...) โ a.any(axis=None, out=None, keepdims=False, *, where=True)argmax(...) โ a.argmax(axis=None, out=None)argmin(...) โ a.argmin(axis=None, out=None)argpartition(...) โ a.argpartition(kth, axis=-1, kind='introselect', order=None)astype(...) โ a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True)byteswap(...) โ a.byteswap(inplace=False)choose(...) โ a.choose(choices, out=None, mode='raise')clip(...) โ a.clip(min=None, max=None, out=None, **kwargs)compress(...) โ a.compress(condition, axis=None, out=None)conj(...) โ a.conj()conjugate(...) โ a.conjugate()copy(...) โ a.copy(order='C')cumprod(...) โ a.cumprod(axis=None, dtype=None, out=None)cumsum(...) โ a.cumsum(axis=None, dtype=None, out=None)diagonal(...) โ a.diagonal(offset=0, axis1=0, axis2=1)dot(...) โ a.dot(b, out=None)dump(...) โ a.dump(file)dumps(...) โ a.dumps()fill(...) โ a.fill(value)flatten(...) โ a.flatten(order='C')getfield(...) โ a.getfield(dtype, offset=0)item(...) โ a.item(*args)itemset(...) โ a.itemset(*args)max(...) โ a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)mean(...) โ a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)min(...) โ a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)newbyteorder(...) โ arr.newbyteorder(new_order='S', /)nonzero(...) โ a.nonzero()prod(...) โ a.prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True)ptp(...) โ a.ptp(axis=None, out=None, keepdims=False)put(...) โ a.put(indices, values, mode='raise')ravel(...) โ a.ravel([order])repeat(...) โ a.repeat(repeats, axis=None)reshape(...) โ a.reshape(shape, order='C')resize(...) โ a.resize(new_shape, refcheck=True)round(...) โ a.round(decimals=0, out=None)searchsorted(...) โ a.searchsorted(v, side='left', sorter=None)setfield(...) โ a.setfield(val, dtype, offset=0)setflags(...) โ a.setflags(write=None, align=None, uic=None)sort(...) โ a.sort(axis=-1, kind=None, order=None)squeeze(...) โ a.squeeze(axis=None)std(...) โ a.std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)sum(...) โ a.sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)swapaxes(...) โ a.swapaxes(axis1, axis2)take(...) โ a.take(indices, axis=None, out=None, mode='raise')tobytes(...) โ a.tobytes(order='C')tofile(...) โ a.tofile(fid, sep="", format="%s")tolist(...) โ a.tolist()tostring(...) โ a.tostring(order='C')trace(...) โ a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)transpose(...) โ a.transpose(*axes)var(...) โ a.var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)view(...) โ a.view([dtype][, type])view()๐ 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 (e.g., converting a regular array to a structured array), then the behavior of the view cannot be predicted just from the superficial appearance of 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.
๐ก Examples:
>>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
Viewing array data using a different type and dtype:
>>> y = x.view(dtype=np.int16, type=np.matrix)
>>> y
matrix([[513]], dtype=int16)
>>> print(type(y))
<class 'numpy.matrix'>
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]
(9, 10)
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[:, 0:2]
>>> y
array([[1, 2],
[4, 5]], 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 array must be C-contiguous
>>> z = y.copy()
>>> z.view(dtype=[('width', np.int16), ('length', np.int16)])
array([[(1, 2)],
[(4, 5)]], dtype=[('width', '<i2'), ('length', '<i2')])
T โ The transposed array. Same as self.transpose(). >>> x = np.array([[1.,2.],[3.,4.]])
>>> x
array([[ 1., 2.],
[ 3., 4.]])
>>> x.T
array([[ 1., 3.],
[ 2., 4.]])
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. >>> x = np.array([1,2,3,4])
>>> x.base is None
True
>>> y = x[2:]
>>> y.base is x
True
ctypes โ An object to simplify the interaction of the array with the ctypes module. >>> import ctypes
>>> x = np.array([[0, 1], [2, 3]], dtype=np.int32)
>>> x.ctypes.data
31962608 # may vary
See Also: numpy.ctypeslibdata โ Python buffer object pointing to the start of the array's data.dtype โ Data-type of the array's elements. >>> x
array([[0, 1],
[2, 3]])
>>> x.dtype
dtype('int32')
See Also: numpy.dtypeflags โ Information about the memory layout of the array. flags object can be accessed dictionary-like... Only the WRITEBACKIFCOPY, UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user.flat โ A 1-D iterator over the array. >>> x = np.arange(1, 7).reshape(2, 3)
>>> x.flat[3]
4
See Also: flatten, flatiterimag โ The imaginary part of the array. >>> x = np.sqrt([1+0j, 0+1j])
>>> x.imag
array([ 0. , 0.70710678])
itemsize โ Length of one array element in bytes. >>> x = np.array([1,2,3], dtype=np.float64)
>>> x.itemsize
8
nbytes โ Total bytes consumed by the elements of the array. >>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.nbytes
480
ndim โ Number of array dimensions. >>> x = np.array([1, 2, 3])
>>> x.ndim
1
real โ The real part of the array. >>> x = np.sqrt([1+0j, 0+1j])
>>> x.real
array([ 1. , 0.70710678])
See Also: numpy.realshape โ Tuple of array dimensions. >>> x = np.array([1, 2, 3, 4])
>>> x.shape
(4,)
See Also: numpy.reshape, ndarray.reshapesize โ Number of elements in the array. >>> x = np.zeros((3, 5, 2), dtype=np.complex128)
>>> x.size
30
strides โ Tuple of bytes to step in each dimension when traversing an array. >>> y = np.reshape(np.arange(2*3*4), (2,3,4))
>>> y.strides
(48, 16, 4)
See Also: numpy.lib.stride_tricks.as_stridedComplex number type composed of two extended-precision floating-point numbers.
Character code: 'G'
Canonical name: numpy.clongdouble
Alias: numpy.clongfloat
Alias: numpy.longcomplex
Alias on this platform (Linux x86_64): numpy.complex256: Complex number type composed of 2 128-bit extended-precision floating-point numbers.
Method resolution order:
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)__and__(self, value, /) โ Return self&value.__array__(...) โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__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.itemset(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.newbyteorder(...) โ newbyteorder(new_order='S', /). Return a new dtype with a different byte order. dtype object with the given change to the byte order.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.ptp(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.Identical to clongdouble (alias). Methods and data descriptors are the same as those listed for clongdouble above.
Complex number type composed of two double-precision floating-point numbers, compatible with Python complex.
Character code: 'D'
Canonical name: numpy.cdouble
Alias: numpy.cfloat
Alias: numpy.complex_
Alias on this platform (Linux x86_64): numpy.complex128: Complex number type composed of 2 64-bit-precision floating-point numbers.
Method resolution order:
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__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.__repr__(self, /) โ Return repr(self).__rfloordiv__(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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object.__round__(...)__and__(self, value, /) โ Return self&value.__array__(...) โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__array_wrap__(...) โ sc.__array_wrap__(obj) return scalar from array__copy__(...)__deepcopy__(...)__divmod__(self, value, /) โ Return divmod(self, value).__format__(...) โ NumPy array scalar formatter__getitem__(self, key, /) โ Return self[key].__invert__(self, /) โ ~self__lshift__(self, value, /) โ Return self<<value.__mod__(self, value, /) โ Return self%value.__or__(self, value, /) โ Return self|value.__rand__(self, value, /) โ Return value&self.__rdivmod__(self, value, /) โ Return divmod(value, self).__reduce__(...) โ Helper for pickle.__rlshift__(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.__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.itemset(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.newbyteorder(...) โ newbyteorder(new_order='S', /). Return a new dtype with a different byte order. dtype object with the given change to the byte order.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.ptp(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.__getattribute__(self, name, /) โ Return getattr(self, name).__getnewargs__(self, /)Complex number type composed of two extended-precision floating-point numbers.
Character code: 'G'
Canonical name: numpy.clongdouble
Alias: numpy.clongfloat
Alias: numpy.longcomplex
Alias on this platform (Linux x86_64): numpy.complex256: Complex number type composed of 2 128-bit extended-precision floating-point numbers.
Method resolution order:
Methods and data descriptors are identical to those of clongdouble (see above).
Complex number type composed of two single-precision floating-point numbers.
Character code: 'F'
Canonical name: numpy.csingle
Alias: numpy.singlecomplex
Alias on this platform (Linux x86_64): numpy.complex64: Complex number type composed of 2 32-bit-precision floating-point numbers.
Method resolution order:
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__complex__(...)__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.__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.__repr__(self, /) โ Return repr(self).__rfloordiv__(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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object.__round__(...)__and__(self, value, /) โ Return self&value.__array__(...) โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__array_wrap__(...) โ sc.__array_wrap__(obj) return scalar from array__copy__(...)__deepcopy__(...)__divmod__(self, value, /) โ Return divmod(self, value).__format__(...) โ NumPy array scalar formatter__getitem__(self, key, /) โ Return self[key].__invert__(self, /) โ ~self__lshift__(self, value, /) โ Return self<<value.__mod__(self, value, /) โ Return self%value.__or__(self, value, /) โ Return self|value.__rand__(self, value, /) โ Return value&self.__rdivmod__(self, value, /) โ Return divmod(value, self).__reduce__(...) โ Helper for pickle.__rlshift__(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.__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.itemset(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.newbyteorder(...) โ newbyteorder(new_order='S', /). Return a new dtype with a different byte order. dtype object with the given change to the byte order.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.ptp(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.Identical to complex128 (alias). Methods and data descriptors are the same as those listed for complex128 above.
Abstract base class of all complex number scalar types that are made up of floating-point numbers.
Method resolution order:
__round__(...)__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_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).__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.itemset(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.newbyteorder(...) โ newbyteorder(new_order='S', /). Return a new dtype with a different byte order. dtype object with the given change to the byte order.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.ptp(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.__hash__ = NoneIdentical to complex64 (alias). Methods and data descriptors are the same as those listed for complex64 above.
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_wrap__(...) โ ๐ฆ sc.__array_wrap__(obj) return scalar from array__copy__(...)__deepcopy__(...)__divmod__(self, value, /) โ ๐ Return divmod(self, value).__format__(...) โ ๐จ๏ธ NumPy array scalar formatter__getitem__(self, key, /) โ ๐ Return self[key].__invert__(self, /) โ ๐ ~self__lshift__(self, value, /) โ ๐ Return self << value.__mod__(self, value, /) โ ๐ Return self % value.__or__(self, value, /) โ ๐ Return self | value.__rand__(self, value, /) โ ๐ Return value & self.__rdivmod__(self, value, /) โ ๐ Return divmod(value, self).__reduce__(...) โ ๐ฅ Helper for pickle.__rlshift__(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.__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.itemset(...) โ ๐ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.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. The new_order code can be any from the following: 'S' โ swap, {'<', 'little'} โ little endian, {'>', 'big'} โ big endian, '=' โ native order, {'|', 'I'} โ ignore. Parameters: new_order (str, optional) โ byte order to force; default is 'S'. Returns: new_dtype (dtype) โ new dtype object.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.ptp(...) โ ๐ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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: structbase โ ๐ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ ๐ Pointer to start of data.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.itemsize โ ๐ The length of one element in bytes.nbytes โ ๐ The length of the scalar in bytes.ndim โ ๐ The number of array dimensions.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.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.
>>> np.datetime64(10, 'Y')
numpy.datetime64('1980')
>>> np.datetime64('1980', 'Y')
numpy.datetime64('1980')
>>> np.datetime64(10, 'D')
numpy.datetime64('1970-01-11')
See arrays.datetime for more information. Character code: 'M'
Method resolution order: datetime64, 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:
__new__(*args, **kwargs) from builtins.type โ Create and return a new 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_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.itemset(...) โ ๐ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.newbyteorder(...) โ ๐ newbyteorder(new_order='S', /). Return a new dtype with a different byte order. See description above.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.ptp(...) โ ๐ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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: structbase โ ๐ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ ๐ Pointer to start of data.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.itemsize โ ๐ The length of one element in bytes.nbytes โ ๐ The length of the scalar in bytes.ndim โ ๐ The number of array dimensions.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.Doubleโprecision floatingโpoint number type, compatible with Python float and C double. Character code: 'd'. Canonical name: numpy.double. Alias: numpy.float_. Alias on this platform (Linux x86_64): 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__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. Raises OverflowError on infinities and ValueError on NaNs. Example: np.double(10.0).as_integer_ratio() โ (10, 1).Static methods:
__new__(*args, **kwargs) from builtins.type โ Create and return a new object.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_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.itemset(...) โ ๐ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.newbyteorder(...) โ ๐ newbyteorder(new_order='S', /). See description above.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.ptp(...) โ ๐ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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: structbase โ ๐ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ ๐ Pointer to start of data.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.itemsize โ ๐ The length of one element in bytes.nbytes โ ๐ The length of the scalar in bytes.ndim โ ๐ The number of array dimensions.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.__getattribute__(self, name, /) โ ๐ Return getattr(self, name).__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.is_integer(self, /) โ ๐ Return True if the float is an integer.Class methods inherited from builtins.float:
__getformat__(typestr, /) from builtins.type โ You probably don't want to use this function.__setformat__(typestr, fmt, /) from builtins.type โ Override the automatic determination of Cโlevel floating point type.fromhex(string, /) from builtins.type โ Create a floatingโpoint number from a hexadecimal string.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.See also: result_type
Examples:
>>> np.dtype(np.int16)
dtype('int16')
>>> np.dtype([('f1', np.int16)])
dtype([('f1', '<i2')])
>>> np.dtype([('f1', [('f1', np.int16)])])
dtype([('f1', [('f1', '<i2')])])
>>> np.dtype([('f1', np.uint64), ('f2', np.int32)])
dtype([('f1', '<u8'), ('f2', '<i4')])
>>> np.dtype([('a','f8'),('b','S10')])
dtype([('a', '<f8'), ('b', 'S10')])
>>> np.dtype("i4, (2,3)f8")
dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])
>>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)])
dtype([('hello', '<i8', (3,)), ('world', 'V10')])
>>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)}))
dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))
>>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]})
dtype([('gender', 'S1'), ('age', 'u1')])
>>> 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; default is 'S'. Returns: new_dtype (dtype).Static methods:
__new__(*args, **kwargs) from _DTypeMeta โ Create and return a new object.Data descriptors defined here:
alignment โ ๐ The required alignment (bytes) of this dataโtype according to the compiler.base โ ๐ฆ Returns dtype for the base element of the subarrays, regardless of their dimension or shape.byteorder โ ๐ A character indicating the byteโorder of this dataโtype object. One of: '=' native, '<' littleโendian, '>' bigโendian, '|' not applicable.char โ ๐ A unique character code for each of the 21 different builtโin types.descr โ ๐ __array_interface__ description of the dataโtype.fields โ ๐ Dictionary of named fields defined for this data type, or None.flags โ ๐ท๏ธ Bitโflags describing how this data type is to be interpreted.hasobject โ ๐งฉ Boolean indicating whether this dtype contains any referenceโcounted objects in any fields or subโdtypes.isalignedstruct โ ๐ Boolean indicating whether the dtype is a struct which maintains field alignment.isbuiltin โ ๐๏ธ Integer indicating how this dtype relates to the builtโin dtypes. (0 = structured, 1 = builtโin, 2 = userโdefined)isnative โ ๐ฅ๏ธ Boolean indicating whether the byte order of this dtype is native to the platform.itemsize โ ๐ The element size of this dataโtype object.kind โ ๐ A character code (one of 'biufcmMOSUV') identifying the general kind of data.metadata โ ๐ Either None or a readonly dictionary of metadata (mappingproxy).name โ ๐ท๏ธ A bitโwidth name for this dataโtype.names โ ๐ Ordered list of field names, or None if there are no fields.ndim โ ๐ Number of dimensions of the subโarray if this data type describes a subโarray, and 0 otherwise.num โ ๐ข A unique number for each of the 21 different builtโin types.shape โ ๐ Shape tuple of the subโarray if this data type describes a subโarray, and () otherwise.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.type โ ๐ท๏ธ (type information)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.
Parameters (kwargs): divide, over, under, invalid โ each with values: 'ignore', 'warn', 'raise', 'call', 'print', 'log'.
See also: seterr, geterr, seterrcall, geterrcall
Methods defined here:
__enter__(self)__exit__(self, *exc_info)__init__(self, *, call=<numpy.core._ufunc_config._unspecified object>, **kwargs) โ Initialize self.Methods inherited from contextlib.ContextDecorator:
__call__(self, func) โ Call self as a function.Data descriptors inherited from contextlib.ContextDecorator:
__dict__ โ dictionary for instance variables (if defined)__weakref__ โ list of weak references to the object (if defined)Machine limits for floating point types.
Attributes:
bits (int) โ The number of bits occupied by the type.eps (float) โ The difference between 1.0 and the next smallest representable float larger than 1.0.epsneg (float) โ The difference between 1.0 and the next smallest representable float less than 1.0.iexp (int) โ The number of bits in the exponent portion of the floating point representation.machar (MachAr) โ The object which calculated these parameters and holds more detailed information.machep (int) โ The exponent that yields eps.max (floating point number) โ The largest representable number.maxexp (int) โ The smallest positive power of the base (2) that causes overflow.min (floating point number) โ 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) โ The approximate decimal resolution of this type, i.e., 10**-precision.tiny (float) โ The smallest positive floating point number with full precision.Parameters: dtype (float, dtype, or instance) โ Kind of floating point dataโtype about which to get information.
See also: MachAr, iinfo, spacing, nextafter
Methods defined here:
__repr__(self) โ Return repr(self).__str__(self) โ Return str(self).Static methods:
__new__(cls, dtype) โ Create and return a new object.Data descriptors:
__dict__ โ dictionary for instance variables (if defined)__weakref__ โ list of weak references to the object (if defined)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.
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.Data descriptors:
base โ ๐ฆ A reference to the array that is iterated over.coords โ ๐ An Nโdimensional tuple of current coordinates.index โ ๐ข Current flat index into the array.Other attributes: __hash__ = None
Abstract base class of all scalar types without predefined length. The actual size of these types depends on the specific np.dtype instantiation.
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_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).__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.itemset(...) โ ๐ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.newbyteorder(...) โ ๐ newbyteorder(new_order='S', /). See description above.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.ptp(...) โ ๐ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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: structbase โ ๐ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ ๐ Pointer to start of data.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.itemsize โ ๐ The length of one element in bytes.nbytes โ ๐ The length of the scalar in bytes.ndim โ ๐ The number of array dimensions.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.Other attributes: __hash__ = None
Extendedโprecision floatingโpoint number type, compatible with C long double but not necessarily with IEEE 754 quadrupleโprecision. Character code: 'g'. Canonical name: numpy.longdouble. Alias: numpy.longfloat. Alias on this platform (Linux x86_64): numpy.float128: 128โbit extendedโprecision floatingโpoint number type.
Methods defined here:
__abs__(self, /) โ ๐ abs(self)__add__(self, value, /) โ ๐ Return self + value.__bool__(self, /) โ ๐ True if self else False__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.Static methods: __new__(*args, **kwargs)
Methods inherited from floating: __round__(...)
Methods inherited from generic (same as float64 above): see the generic method list for details.
Data descriptors inherited from generic (same as float64): see above.
Halfโprecision floatingโpoint number type. Character code: 'e'. Canonical name: numpy.half. Alias on this platform: numpy.float16: 16โbitโprecision floatingโpoint number type: sign bit, 5 bits exponent, 10 bits mantissa.
Methods defined here:
__abs__(self, /) โ ๐ abs(self)__add__(self, value, /) โ ๐ Return self + value.__bool__(self, /) โ ๐ True if self else False__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).Static methods: __new__(*args, **kwargs)
Methods inherited from floating: __round__(...)
Methods inherited from generic (same as float64): see above.
Data descriptors inherited from generic (same as float64): see above.
Singleโprecision floatingโpoint number type, compatible with C float. Character code: 'f'. Canonical name: numpy.single. Alias on this platform: numpy.float32: 32โbitโprecision floatingโpoint number type: sign bit, 8 bits exponent, 23 bits mantissa.
Methods defined here:
__abs__(self, /) โ ๐ abs(self)__add__(self, value, /) โ ๐ Return self + value.__bool__(self, /) โ ๐ True if self else False__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).Static methods: __new__(*args, **kwargs)
Methods inherited from floating: __round__(...)
Methods inherited from generic (same as float64): see above.
Data descriptors inherited from generic (same as float64): see above.
Note: For brevity, the full list of inherited generic methods and data descriptors for float128, float16, and float32 have been omitted. They are identical to those listed for float64 and complexfloating.
๐ See help(type) for accurate signature.
__round__(...)__and__(self, value, /) โ ๐ Return self&value.__array__(...) โ ๐ฆ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__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.itemset(...) โ โ๏ธ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.newbyteorder(...) โ ๐ newbyteorder(new_order='S', /) โ Return a new dtype with a different byte order. Changes are also made in all fields and sub-arrays. Options: 'S' (swap), '<' (little), '>' (big), '=' (native), '|' (ignore).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.ptp(...) โ ๐ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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.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: structbase โ ๐ฆ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ ๐ Pointer to start of data.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.itemsize โ ๐ The length of one element in bytes.nbytes โ ๐พ The length of the scalar in bytes.ndim โ ๐ข The number of array dimensions.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.float64(x=0, /) โ Double-precision floating-point number type, compatible with Python float and C double.
'd'numpy.doublenumpy.float_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
__abs__(self, /) โ โ
abs(self)__add__(self, value, /) โ โ Return self+value.__bool__(self, /) โ โ
True if self else False__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. Raise OverflowError on infinities and ValueError on NaNs.__new__(*args, **kwargs) from builtins.type โ ๐ Create and return a new object. See help(type) for accurate signature.__round__(...)__and__, __array__, __array_wrap__, __copy__, __deepcopy__, __format__, __getitem__, __invert__, __lshift__, __or__, __rand__, __reduce__, __rlshift__, __ror__, __rrshift__, __rshift__, __rxor__, __setstate__, __sizeof__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view (see class generic for details).T, __array_interface__, __array_priority__, __array_struct__, base, data, dtype, flags, flat, imag, itemsize, nbytes, ndim, real, shape, size, strides (see class generic for details).__ceil__(self, /) โ ๐ Return the ceiling as an Integral.__floor__(self, /) โ ๐ Return the floor as an Integral.__getattribute__(self, name, /) โ ๐ Return getattr(self, name).__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.is_integer(self, /) โ โ
Return True if the float is an integer.__getformat__(typestr, /) from builtins.type โ ๐ง You probably don't want to use this function. It exists mainly to be used in Python's test suite.__setformat__(typestr, fmt, /) from builtins.type โ ๐ง Override the automatic determination of C-level floating point type.fromhex(string, /) from builtins.type โ ๐ค Create a floating-point number from a hexadecimal string.Abstract base class of all floating-point scalar types.
๐ Method resolution order: floating, inexact, number, generic, builtins.object
__round__(...)__abs__, __add__, __and__, __array__, __array_wrap__, __bool__, __copy__, __deepcopy__, __divmod__, __eq__, __float__, __floordiv__, __format__, __ge__, __getitem__, __gt__, __int__, __invert__, __le__, __lshift__, __lt__, __mod__, __mul__, __ne__, __neg__, __or__, __pos__, __pow__, __radd__, __rand__, __rdivmod__, __reduce__, __rfloordiv__, __rlshift__, __rmod__, __rmul__, __ror__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __setstate__, __sizeof__, __sub__, __truediv__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view (see class generic for details).T, __array_interface__, __array_priority__, __array_struct__, base, data, dtype, flags, flat, imag, itemsize, nbytes, ndim, real, shape, size, strides (see class generic for details).__hash__ = Noneformat_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
dtype โ dtype: The converted data-type.formats โ str or list of str: The format description, either as a comma-separated string or a list.names โ str or list/tuple of str: The field names.titles โ sequence: Sequence of title strings.aligned โ bool, optional: If True, align fields by padding as C-compiler would. Default False.byteorder โ str, optional: If specified, all fields will be changed to the provided byte-order.dtype, typename, sctype2char
>>> np.format_parser(['<f8', '<i4', '<a5'], ['col1', 'col2', 'col3'],
... ['T1', 'T2', 'T3']).dtype
dtype([(('T1', 'col1'), '<f8'), (('T2', 'col2'), '<i4'), (('T3', 'col3'), 'S5')])
>>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
... []).dtype
dtype([('col1', '<f8'), ('col2', '<i4'), ('col3', '<S5')])
>>> np.format_parser(['<f8', '<i4', '<a5'], [], []).dtype
dtype([('f0', '<f8'), ('f1', '<i4'), ('f2', 'S5')])
__init__(self, formats, names, titles, aligned=False, byteorder=None) โ Initialize self.__dict__ โ dictionary for instance variables (if defined)__weakref__ โ list of weak references to the object (if defined)Base class for numpy scalar types. Class from which most (all?) numpy scalar types are derived. Exposes the same API as ndarray.
__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_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).__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.itemset(...) โ โ๏ธ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.newbyteorder(...) โ ๐ newbyteorder(new_order='S', /) โ Return a new dtype with a different byte order. Options: 'S' (swap), '<' (little), '>' (big), '=' (native), '|' (ignore).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.ptp(...) โ ๐ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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.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: structbase โ ๐ฆ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ ๐ Pointer to start of data.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.itemsize โ ๐ The length of one element in bytes.nbytes โ ๐พ The length of the scalar in bytes.ndim โ ๐ข The number of array dimensions.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.__hash__ = NoneHalf-precision floating-point number type.
'e'numpy.halfnumpy.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
__abs__(self, /) โ โ
abs(self)__add__(self, value, /) โ โ Return self+value.__bool__(self, /) โ โ
True if self else False__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.__new__(*args, **kwargs) from builtins.type โ ๐ Create and return a new object.__round__(...)__and__, __array__, __array_wrap__, __copy__, __deepcopy__, __format__, __getitem__, __invert__, __lshift__, __or__, __rand__, __reduce__, __rlshift__, __ror__, __rrshift__, __rshift__, __rxor__, __setstate__, __sizeof__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view (see class generic for details).T, __array_interface__, __array_priority__, __array_struct__, base, data, dtype, flags, flat, imag, itemsize, nbytes, ndim, real, shape, size, strides (see class generic for details).iinfo(int_type) โ Machine limits for integer types.
bits โ int: The number of bits occupied by the type.min โ int: The smallest integer expressible by the type.max โ int: The largest integer expressible by the type.int_type โ integer type, dtype, or instance: The kind of integer data type to get information about.finfo โ The equivalent for floating point data types.
>>> ii16 = np.iinfo(np.int16)
>>> ii16.min
-32768
>>> ii16.max
32767
>>> ii32 = np.iinfo(np.int32)
>>> ii32.min
-2147483648
>>> ii32.max
2147483647
>>> ii32 = np.iinfo(np.int32(10))
>>> ii32.min
-2147483648
>>> ii32.max
2147483647
__init__(self, int_type) โ Initialize self.__repr__(self) โ Return repr(self).__str__(self) โ String representation.max โ Maximum value of given dtype.min โ Minimum value of given dtype.__dict__ โ dictionary for instance variables (if defined)__weakref__ โ list of weak references to the object (if defined)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
__abs__, __add__, __and__, __array__, __array_wrap__, __bool__, __copy__, __deepcopy__, __divmod__, __eq__, __float__, __floordiv__, __format__, __ge__, __getitem__, __gt__, __int__, __invert__, __le__, __lshift__, __lt__, __mod__, __mul__, __ne__, __neg__, __or__, __pos__, __pow__, __radd__, __rand__, __rdivmod__, __reduce__, __rfloordiv__, __rlshift__, __rmod__, __rmul__, __ror__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __setstate__, __sizeof__, __sub__, __truediv__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view (see class generic for details).T, __array_interface__, __array_priority__, __array_struct__, base, data, dtype, flags, flat, imag, itemsize, nbytes, ndim, real, shape, size, strides (see class generic for details).__hash__ = NoneSigned integer type, compatible with Python int and C long.
'l'numpy.int_numpy.int64: 64-bit signed integer (``-9_223_372_036_854_775_808`` to ``9_223_372_036_854_775_807``).numpy.intp: Signed integer large enough to fit pointer, compatible with C intptr_t.๐ Method resolution order: int64, signedinteger, integer, number, generic, builtins.object
__abs__(self, /) โ โ
abs(self)__add__(self, value, /) โ โ Return self+value.__and__(self, value, /) โ ๐ Return self&value.__bool__(self, /) โ โ
True if self else False__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.__new__(*args, **kwargs) from builtins.type โ ๐ Create and return a new object.__round__(...)denominator โ denominator of value (1)numerator โ numerator of value (the value itself)denominator โ denominator of value (1)numerator โ numerator of value (the value itself)__array__, __array_wrap__, __copy__, __deepcopy__, __format__, __getitem__, __reduce__, __setstate__, __sizeof__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view (see class generic for details).T, __array_interface__, __array_priority__, __array_struct__, base, data, dtype, flags, flat, imag, itemsize, nbytes, ndim, real, shape, size, strides (see class generic for details).๐ Note: The above condenses repeated inherited method lists by referencing the base class. Full descriptions are available in the class generic definition.
๐ Signed integer type, compatible with C char.
'b'numpy.bytenumpy.int8: 8-bit signed integer (-128 to 127).๐ Method resolution order:
๐ ๏ธ 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__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 suitable for use as an index.__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.โ๏ธ Static methods defined here:
__new__(*args, **kwargs) from builtins.type โ Create and return a new object.๐ Methods inherited from integer:
__round__(...)๐ 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_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.itemset(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.newbyteorder(...) โ newbyteorder(new_order='S', /) โ Return a new dtype with a different byte order. Changes are made in all fields and sub-arrays. The new_order code can be any from: 'S' (swap), '<'/'little' (little endian), '>'/'big' (big endian), '=' (native), '|'/'I' (ignore). Parameters: new_order : str, optional โ Byte order to force. Default ('S') swaps current byte order. Returns: new_dtype : dtype โ New dtype object with the given change.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.ptp(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.๐ Signed integer type, compatible with C short.
'h'numpy.shortnumpy.int16: 16-bit signed integer (-32_768 to 32_767).๐ Method resolution order: int16, signedinteger, integer, number, generic, builtins.object
๐ ๏ธ Methods defined here: same as int8 (operator methods, static __new__).
๐ Methods inherited from integer: __round__
๐ Data descriptors inherited from integer: denominator, numerator
๐ Methods inherited from generic: same as listed for int8 (including newbyteorder, etc.)
๐ Data descriptors inherited from generic: same as int8.
๐ Signed integer type, compatible with C int.
'i'numpy.intcnumpy.int32: 32-bit signed integer (-2_147_483_648 to 2_147_483_647).๐ Method resolution order: int32, signedinteger, integer, number, generic, builtins.object
๐ ๏ธ Methods defined here: same as int8.
๐ Inherited from integer: __round__
๐ Data descriptors from integer: denominator, numerator
๐ Methods inherited from generic: same as int8.
๐ Data descriptors inherited from generic: same as int8.
๐ Signed integer type, compatible with Python int and C long.
'l'numpy.int_numpy.int64: 64-bit signed integer (-9_223_372_036_854_775_808 to 9_223_372_036_854_775_807).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: same as int8 (plus all operator methods).
๐ Inherited from integer: __round__
๐ Data descriptors from integer: denominator, numerator
๐ Methods inherited from generic: same as int8.
๐ Data descriptors inherited from generic: same as int8.
๐ Abstract base class of all integer scalar types.
๐ Method resolution order: integer, number, generic, builtins.object
๐ ๏ธ Methods defined here:
__round__(...)๐ Data descriptors defined here:
denominator โ denominator of value (1)numerator โ numerator of value (the value itself)๐ Methods inherited from generic: same as int8 (including all operator methods, scalar methods, newbyteorder, etc.).
๐ Data descriptors inherited from generic: same as int8.
๐ Note: __hash__ = None (data and other attributes inherited from generic).
๐ Alias for int64. Same description, MRO, methods, and descriptors as int64.
๐ Alias for int32. Same as int32.
๐ Alias for int64. Same as int64.
๐ Complex number type composed of two extended-precision floating-point numbers.
'G'numpy.clongdoublenumpy.clongfloat, numpy.longcomplexnumpy.complex256: Complex number type composed of 2 128-bit extended-precision floating-point numbers.๐ Method resolution order: complex256, 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__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.โ๏ธ Static methods defined here:
__new__(*args, **kwargs) from builtins.type โ Create and return a new object.๐ (Methods and data descriptors inherited from complexfloating, inexact, number, generic would be similar to the integer case, with complex-specific methods.)
csingle = class complex64Single-precision complex floating-point number type, compatible with C float complex.
Character code: 'F'
Canonical name: numpy.csingle
Alias: numpy.complex64: 64-bit complex floating-point number type.
Method resolution order:
See help(type) for accurate signature.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)__and__(self, value, /) โ Return self&value.__array__(...) โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__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.itemset(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.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. The new_order code can be any from the following:new_order : str, optional โ Byte order to force; a value from the byte order specifications above. The default value ('S') results in swapping the current byte order. Returns: new_dtype : dtype โ New dtype object with the given change to the byte order.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.ptp(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.cdouble = class complex128Double-precision complex floating-point number type, compatible with Python complex and C double complex.
Character code: 'D'
Canonical name: numpy.cdouble
Alias: numpy.complex128: 128-bit complex floating-point number type.
Method resolution order:
See help(type) for accurate signature.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)Same as inherited from csingle (see above).
Same as inherited from csingle (see above).
cfloat = class complex128Double-precision complex floating-point number type, compatible with Python complex and C double complex.
Character code: 'D'
Canonical name: numpy.cdouble
Alias: numpy.complex128
Method resolution order:
See help(type) for accurate signature.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)Same as inherited from csingle (see above).
Same as inherited from csingle (see above).
clongdouble = class complex192 (on Linux x86_64)Extended-precision complex floating-point number type, compatible with C long double complex but not necessarily with IEEE 754 quadruple-precision.
Character code: 'G'
Canonical name: numpy.clongdouble
Alias: numpy.longcomplex
Alias on this platform (Linux x86_64): numpy.complex192: 192-bit complex floating-point number type.
Method resolution order:
See help(type) for accurate signature.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)Same as inherited from csingle (see above).
Same as inherited from csingle (see above).
clongfloat = class complex192 (on Linux x86_64)Extended-precision complex floating-point number type, compatible with C long double complex but not necessarily with IEEE 754 quadruple-precision.
Character code: 'G'
Canonical name: numpy.clongdouble
Alias: numpy.longcomplex
Alias on this platform (Linux x86_64): numpy.complex192: 192-bit complex floating-point number type.
Method resolution order:
See help(type) for accurate signature.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)Same as inherited from csingle (see above).
Same as inherited from csingle (see above).
complex64 = class complex64Single-precision complex floating-point number type, compatible with C float complex.
Character code: 'F'
Canonical name: numpy.csingle
Alias: numpy.complex64: 64-bit complex floating-point number type.
Method resolution order:
See help(type) for accurate signature.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)Same as inherited from csingle (see above).
Same as inherited from csingle (see above).
complex128 = class complex128Double-precision complex floating-point number type, compatible with Python complex and C double complex.
Character code: 'D'
Canonical name: numpy.cdouble
Alias: numpy.complex128: 128-bit complex floating-point number type.
Method resolution order:
See help(type) for accurate signature.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)Same as inherited from csingle (see above).
Same as inherited from csingle (see above).
complex192 = class complex192Extended-precision complex floating-point number type, compatible with C long double complex but not necessarily with IEEE 754 quadruple-precision.
Character code: 'G'
Canonical name: numpy.longcomplex
Alias: numpy.complex192: 192-bit complex floating-point number type.
Method resolution order:
See help(type) for accurate signature.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)Same as inherited from csingle (see above).
Same as inherited from csingle (see above).
complex256 = class complex256Quarter-precision complex floating-point number type, compatible with C float complex? (Platform-specific)
Character code: 'G'
Canonical name: numpy.clongdouble
Alias: numpy.complex256: 256-bit complex floating-point number type.
Method resolution order:
See help(type) for accurate signature.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)Same as inherited from csingle (see above).
Same as inherited from csingle (see above).
compound = class genericCompound data type, used for structured arrays.
Character code: 'V'
Method resolution order:
See help(type) for accurate signature.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__and__(self, value, /) โ Return self&value.__array__(...) โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__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.itemset(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.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. The new_order code can be any from the following:new_order : str, optional โ Byte order to force; a value from the byte order specifications above. The default value ('S') results in swapping the current byte order. Returns: new_dtype : dtype โ New dtype object with the given change to the byte order.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.ptp(...) โ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.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.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.tobytes(...)๐ฅ Parameters: order : {'C', 'F', 'A'}, optional. Default 'C'.
๐ค Returns: s : bytes โ Python bytes exhibiting a copy of a's raw data.
๐ก Example:
>>> 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(...)๐ฅ Parameters: fid : file or str or Path | sep : str (default "") | format : str (default "%s")
๐ Notes: Always writes in 'C' order. Data can be recovered via fromfile(). Writing binary with sep="" is equivalent to file.write(a.tobytes()).
โ ๏ธ Limitations: Endianness/precision lost; not for archival. Cannot be used with compressed files or objects without fileno().
tostring(...)๐๏ธ Deprecated since 1.19.0. Alias for tobytes.
trace(...)๐ See numpy.trace.
transpose(...)๐ฅ Parameters: axes : None, tuple of ints, or n ints.
๐ค Returns: out : ndarray โ view with axes permuted.
๐ก Example:
>>> a = np.array([[1, 2], [3, 4]])
>>> a.transpose()
array([[1, 3],
[2, 4]])
view(...)๐ฅ Parameters: dtype (optional), type (optional).
โ ๏ธ Notes: Two uses โ reinterpret dtype or return subclass instance. Behavior depends on memory layout.
๐ก Examples:
>>> x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)])
>>> y = x.view(dtype=np.int16, type=np.matrix)
>>> y
matrix([[513]], dtype=int16)
__array_interface__ โ Array protocol: Python side.__array_struct__ โ Array protocol: C-struct side.base โ Base object if memory is from some other object.ctypes โ Simplifies interaction with ctypes module.data โ Python buffer object pointing to start of array's data.dtype โ Data-type of array elements.flags โ Memory layout information (C_CONTIGUOUS, F_CONTIGUOUS, OWNDATA, WRITEABLE, ALIGNED, etc.).flat โ 1-D flat iterator over the array.imag โ Imaginary part of the array.itemsize โ Length of one array element in bytes.nbytes โ Total bytes consumed by elements.ndim โ Number of array dimensions.real โ Real part of the array.shape โ Tuple of array dimensions.size โ Number of elements in the array.strides โ Tuple of bytes to step in each dimension.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.
๐ฅ Parameters:
filename : str, file-like, or pathlib.Pathdtype : data-type, optional (default uint8)mode : {'r+', 'r', 'w+', 'c'}, optionaloffset : int, optionalshape : tuple, optionalorder : {'C', 'F'}, optional๐ Attributes: filename, offset, mode.
๐ ๏ธ Methods: flush โ writes changes to disk.
โ ๏ธ Notes: Cannot be larger than 2GB on 32-bit systems. Extending file beyond current size fills with zero bytes on POSIX.
๐ก Examples:
>>> data = np.arange(12, dtype='float32')
>>> data.resize((3,4))
>>> from tempfile import mkdtemp
>>> import os.path as path
>>> filename = path.join(mkdtemp(), 'newfile.dat')
>>> fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))
>>> fp[:] = data[:]
>>> fp.flush()
>>> 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)
ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)
An array object represents a multidimensional, homogeneous array of fixed-size items.
๐ฅ Parameters (for __new__):
shape : tuple of intsdtype : data-type, optionalbuffer : object exposing buffer interface, optionaloffset : int, optionalstrides : tuple of ints, optionalorder : {'C', 'F'}, optional๐ Attributes: T, data, dtype, flags, flat, imag, real, size, itemsize, nbytes, ndim, shape, strides, ctypes, base.
๐ Notes: Two modes of creation (buffer vs None). No __init__ needed.
๐ก Examples:
>>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000], # random
[ nan, 2.5e-323]])
>>> np.ndarray((2,), buffer=np.array([1,2,3]),
... offset=np.int_().itemsize,
... dtype=int)
array([2, 3])
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__and__(self, value, /) โ Return self&value.__array__(...) โ Returns reference if dtype unchanged, else copy.__array_function__(...)__array_prepare__(...) โ Object of same type.__array_ufunc__(...)__array_wrap__(...) โ Object of same type.__bool__(self, /) โ True if self else False__complex__(...)__contains__(self, key, /) โ Return key in self.__copy__(...) โ Copy of array (equivalent to a.copy(order='K')).__deepcopy__(...) โ Deep copy.__delitem__(self, key, /) โ Delete self[key].__divmod__(self, value, /) โ Return divmod(self, value).__eq__(self, value, /) โ Return self==value.__float__(self, /) โ float(self)__floordiv__(self, value, /) โ Return self//value.__format__(...) โ Default object formatter.__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, /) โ Convert to integer for index.__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__(...) โ 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__(...) โ For unpickling.__sizeof__(...) โ Size of object in memory.__str__(self, /) โ Return str(self).__sub__(self, value, /) โ Return self-value.__truediv__(self, value, /) โ Return self/value.__xor__(self, value, /) โ Return self^value.all(...) โ Returns True if all elements evaluate to True.any(...) โ Returns True if any elements evaluate to True.argmax(...) โ Indices of maximum values along axis.argmin(...) โ Indices of minimum values along axis.argpartition(...) โ Indices that would partition array.argsort(...) โ Indices that would sort array.astype(...) โ Copy cast to specified type.byteswap(...) โ Swap bytes of array elements.choose(...) โ Construct array from choices.clip(...) โ Limit values to [min, max].compress(...) โ Return selected slices along axis.conj(...) โ Complex-conjugate all elements.conjugate(...) โ Complex conjugate element-wise.copy(...) โ Return copy of array with order parameter.cumprod(...) โ Cumulative product along axis.cumsum(...) โ Cumulative sum along axis.diagonal(...) โ Return specified diagonals.dot(...) โ Dot product of two arrays.dump(...) โ Dump pickle to file.dumps(...) โ Return pickle as string.fill(...) โ Fill array with scalar value.flatten(...) โ Copy collapsed into one dimension.getfield(...) โ Returns field of array as given type.item(...) โ Copy element to Python scalar.itemset(...) โ Insert scalar into array.max(...) โ Maximum along axis.mean(...) โ Average of elements along axis.min(...) โ Minimum along axis.newbyteorder(...) โ Return array with different byte order.nonzero(...) โ Indices of non-zero elements.partition(...) โ Rearrange elements so kth element is in sorted position.prod(...) โ Product of elements over axis.ptp(...) โ Peak to peak (max - min) along axis.put(...) โ Set a.flat[n] = values[n].ravel(...) โ Return flattened array.repeat(...) โ Repeat elements.reshape(...) โ Return array with new shape.resize(...) โ Change shape in-place.round(...) โ Round elements to given decimals.searchsorted(...) โ Find indices to insert values maintaining order.setfield(...) โ Put value into field defined by dtype.setflags(...) โ Set WRITEABLE, ALIGNED, etc.sort(...) โ Sort array in-place.squeeze(...) โ Remove axes of length one.std(...) โ Standard deviation along axis.sum(...) โ Sum of elements over axis.swapaxes(...) โ Interchange axes.take(...) โ Return array from elements at given indices.tobytes(...) โ Construct Python bytes of raw data.tofile(...) โ Write array to file.tolist(...) โ Return array as nested list.tostring(...) โ Alias for tobytes (deprecated).trace(...) โ Sum along diagonals.transpose(...) โ View with axes transposed.var(...) โ Variance along axis.view(...) โ New view with same data.__hash__ = Nonendarray(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 constructor (ndarray(โฆ)) for instantiating an array.
For more information, refer to the numpy module and examine the methods and attributes of an array.
out : ndarray โ Array object with given shape, dtype, order.
array : Construct an array.zeros : Create an array of zeros.empty : Create an empty array.zeros_like : Create an array of zeros with same shape and type.empty_like : Create an empty array with same shape and type.full : Create an array of a given value.full_like : Create an array of a given value with same shape and type.There are two modes of creating an array using __new__:
buffer is None, then only shape, dtype, and order are used.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 __new__.
These examples illustrate the low-level ndarray constructor:
>>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[0.0e+000, 0.0e+000],
[ nan, nan]]) # uninitialized
>>> np.ndarray((2,), buffer=np.array([1,2,3]),
... offset=np.int_().itemsize,
... dtype=int) # offset = 8 bytes
array([2, 3])
From an iterable, use np.array:
>>> np.array([[1,2],[3,4]])
array([[1, 2],
[3, 4]])
all(axis=None, out=None, keepdims=False, *, where=True)any(axis=None, out=None, keepdims=False, *, where=True)argmax(axis=None, out=None, *, keepdims=False)argmin(axis=None, out=None, *, keepdims=False)argpartition(kth, axis=-1, kind='introselect', order=None)argsort(axis=-1, kind=None, order=None)astype(dtype, order='K', casting='unsafe', subok=True, copy=True)byteswap(inplace=False)choose(choices, out=None, mode='raise')clip(min=None, max=None, out=None, **kwargs)compress(condition, axis=None, out=None)conj()conjugate()copy(order='C')cumprod(axis=None, dtype=None, out=None)cumsum(axis=None, dtype=None, out=None)diagonal(offset=0, axis1=0, axis2=1)dot(b, out=None)dump(file)dumps()fill(value)flatten(order='C')getfield(dtype, offset=0)item(*args)itemset(*args)max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)min(axis=None, out=None, keepdims=False, initial=<no value>, where=True)newbyteorder(new_order='S', /)nonzero()partition(kth, axis=-1, kind='introselect', order=None)prod(axis=None, dtype=None, out=None, keepdims=False, initial=1, where=True)ptp(axis=None, out=None, keepdims=False)put(indices, values, mode='raise')ravel([order])repeat(repeats, axis=None)reshape(shape, order='C')resize(new_shape, refcheck=True)round(decimals=0, out=None)searchsorted(v, side='left', sorter=None)setfield(val, dtype, offset=0)setflags(write=None, align=None, uic=None)sort(axis=-1, kind=None, order=None)squeeze(axis=None)std(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)sum(axis=None, dtype=None, out=None, keepdims=False, initial=0, where=True)swapaxes(axis1, axis2)take(indices, axis=None, out=None, mode='raise')tobytes(order='C')tofile(fid, sep="", format="%s")tolist()tostring(order='C')trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)transpose(*axes)var(axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True)view([dtype][, type])__new__(*args, **kwargs) from builtins.type โ Create and return a new object.T โ The transposed array.__array_finalize__ โ None.__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.ctypes โ An object to simplify interaction with the ctypes module.data โ Python buffer object pointing to start of array's data.dtype โ Data-type of the array's elements.flags โ Information about the memory layout of the array.flat โ A 1-D iterator over the array.imag โ The imaginary part of the array.itemsize โ Length of one array element in bytes.nbytes โ Total bytes consumed by the elements.ndim โ Number of array dimensions.real โ The real part of the array.shape โ Tuple of array dimensions.size โ Number of elements in the array.strides โ Tuple of bytes to step in each dimension.__hash__ = Nonendenumerate(arr)
Multidimensional index iterator. Returns an iterator yielding pairs of array coordinates and values.
ndindex, flatiter>>> 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
__init__(self, arr) โ Initialize self.__iter__(self)__next__(self) โ Returns index tuple and array value.__dict__ โ dictionary for instance variables (if defined)__weakref__ โ list of weak references to the object (if defined)ndindex(*shape)
An N-dimensional iterator object to index arrays. Given the shape of an array, iterates over the N-dimensional index.
ndenumerate, flatiter>>> 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)
__init__(self, *shape) โ Initialize self.__iter__(self)__next__(self) โ Returns index tuple.ndincr(self) โ Increment the multi-dimensional index by one. โ ๏ธ Deprecated since 1.20.0__dict____weakref__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.
dtypes โ tuple of dtype(s) โ Data types of values provided.finished โ bool โ Whether iteration is finished.has_delayed_bufalloc โ bool โ Whether delayed buffer allocation is active.has_index โ bool โ Whether index tracking is enabled.has_multi_index โ bool โ Whether multi-index tracking is enabled.index โ Access index when c_index or f_index flag used.iterationneedsapi โ bool โ Whether iteration requires Python API.iterindex โ int โ Index matching iteration order.itersize โ int โ Size of the iterator.itviews โ Structured view(s) of operands in memory.multi_index โ Access multi-index when multi_index flag used.ndim โ int โ Dimensions of the iterator.nop โ int โ Number of iterator operands.operands โ tuple of operand(s) โ Arrays to be iterated over.shape โ tuple of ints โ Shape of the iterator.value โ Value of operands at current iteration.nditer supersedes flatiter. The iterator implementation is also exposed by the NumPy C API.
>>> 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]
>>> a = np.arange(2)+1
>>> b = np.arange(3)+1
>>> outer_it(a,b)
array([[1, 2, 3],
[2, 4, 6]])
__copy__(...)__delitem____enter____exit____getitem____init____iter____len____next____setitem__close() โ Resolve all writeback semantics.copy() โ Get a copy of the iterator in its current state.debug_print() โ Print current state of the nditer instance.enable_external_loop() โ Modify iterator to behave as if external_loop flag was specified.iternext() โ Perform a single internal iteration without returning result.remove_axis(i) โ Remove axis i from the iterator.remove_multi_index() โ Remove multi-index tracking.reset() โ Reset iterator to initial state.dtypesfinishedhas_delayed_bufallochas_indexhas_multi_indexindexiterationneedsapiiterindexiterrangeitersizeitviewsmulti_indexndimnopoperandsshapevalueAbstract base class of all numeric scalar types.
number โ generic โ builtins.object
__abs____add____and____array____array_wrap____bool____copy____deepcopy____divmod____eq____float____floordiv____format____ge____getitem____gt____int____invert____le____lshift____lt____mod____mul____ne____neg____or____pos____pow____radd____rand____rdivmod____reduce____rfloordiv____rlshift____rmod____rmul____ror____rpow____rrshift____rshift____rsub____rtruediv____rxor____setstate____sizeof____sub____truediv____xor__allanyargmaxargminargsortastypebyteswapchooseclipcompressconjconjugatecopycumprodcumsumdiagonaldumpdumpsfillflattengetfielditemitemsetmaxmeanminnewbyteordernonzeroprodptpputravelrepeatreshaperesizeroundsearchsortedsetfieldsetflagssortsqueezestdsumswapaxestaketobytestofiletolisttostringtracetransposevarviewT__array_interface____array_priority____array_struct__basedatadtypeflagsflatimagitemsizenbytesndimrealshapesizestrides__hash__ = NoneAny Python object. Character code: 'O'
object_ โ generic โ builtins.object
__add____call____contains____delattr____delitem____eq____ge____getattribute____getitem____gt____hash____iadd____imul____le____len____lt____mul____ne____rmul____setattr____setitem____new__(*args, **kwargs) from builtins.typeSame as for number class above.
Same as for number class above.
class generic(builtins.object)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.
The new_order code can be any from the following:
'S' โ swap dtype from current to opposite endian{'<', 'little'} โ little endian{'>', 'big'} โ big endian'=' โ native order{'|', 'I'} โ ignore (no change to byte order)Parameters
new_order : str, optional โ Byte order to force; a value from the byte order specifications above. The default value ('S') results in swapping the current byte order.Returns
new_dtype : dtype โ New dtype object with the given change to the byte order.The following methods are scalar methods identical to the corresponding array attribute. Please see ndarray for details.
nonzero(...)prod(...)ptp(...)put(...)ravel(...)repeat(...)reshape(...)resize(...)round(...)searchsorted(...)setfield(...)setflags(...)sort(...)squeeze(...)std(...)sum(...)swapaxes(...)take(...)tobytes(...)tofile(...)tolist(...)tostring(...)trace(...)transpose(...)var(...)view(...)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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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 poly1d(builtins.object)A one-dimensional polynomial class.
Note: This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.
A convenience class, used to encapsulate "natural" operations on polynomials so that said operations may take on their customary form in code (see Examples).
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 x^2 + 2x + 3, whereas poly1d([1, 2, 3], True) returns one that represents (x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x -6.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).>>> p = np.poly1d([1, 2, 3])
>>> print(np.poly1d(p))
2
1 x + 2 x + 3
>>> p(0.5)
4.25
>>> 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.
>>> p.c
array([1, 2, 3])
>>> p.order
2
>>> 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.]))
>>> p**2 # square of polynomial
poly1d([ 1, 4, 10, 12, 9])
>>> np.square(p) # square of individual coefficients
array([1, 4, 9])
>>> p = np.poly1d([1,2,3], variable='z')
>>> print(p)
2
1 z + 2 z + 3
>>> np.poly1d([1, 2], True)
poly1d([ 1., -3., 2.])
>>> np.poly1d([1, -1]) * np.poly1d([1, -2])
poly1d([ 1, -3, 2])
__add__(self, other)__array__(self, t=None)__call__(self, val) โ Call self as a function.__div__(self, other)__eq__(self, other) โ Return self==value.__getitem__(self, val)__init__(self, c_or_r, r=False, variable=None) โ Initialize self. See help(type(self)) for accurate signature.__iter__(self)__len__(self)__mul__(self, other)__ne__(self, other) โ Return self!=value.__neg__(self)__pos__(self)__pow__(self, val)__radd__(self, other)__rdiv__(self, other)__repr__(self) โ Return repr(self).__rmul__(self, other)__rsub__(self, other)__rtruediv__ = __rdiv__(self, other)__setitem__(self, key, val)__str__(self) โ Return str(self).__sub__(self, other)__truediv__ = __div__(self, other)deriv(self, m=1) โ Return a derivative of this polynomial. See polyder for full documentation.integ(self, m=1, k=0) โ Return an antiderivative (indefinite integral) of this polynomial. See polyint for full documentation.o โ The order or degree of the polynomialorder โ The order or degree of the polynomialr โ The roots of the polynomial, where self(x) == 0roots โ The roots of the polynomial, where self(x) == 0variable โ The name of the polynomial variable__dict__ โ dictionary for instance variables (if defined)__weakref__ โ list of weak references to the object (if defined)c โ The polynomial coefficientscoef โ The polynomial coefficientscoefficients โ The polynomial coefficientscoeffs โ The polynomial coefficients__hash__ = Noneclass recarray(ndarray)Construct an ndarray that allows field access using attributes.
Arrays may have a data-types containing fields, analogous to columns in a spread sheet. An example is [(x, int), (y, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['x'] and arr['y']. Record arrays allow the fields to be accessed as members of the array, using arr.x and arr.y.
shape : 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.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.rec : recarray โ Empty array of the given shape and type.core.records.fromrecords โ Construct a record array from data.record โ fundamental data-type for recarray.format_parser โ determine a data-type from formats, names, titles.This constructor can be compared to empty: it creates a new record array but does not fill it with data. To create a record array from data, use one of the following methods:
arr.view(np.recarray)buf keyword.np.rec.fromrecords.>>> 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.])
>>> x = x.view(np.recarray)
>>> x.x
array([1., 3.])
>>> x.y
array([2, 4])
>>> 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')])
recarrayndarraybuiltins.object__array_finalize__(self, obj) โ None.__getattribute__(self, attr) โ Return getattr(self, name).__getitem__(self, indx) โ Return self[key].__repr__(self) โ Return repr(self).__setattr__(self, attr, val) โ Implement setattr(self, name, value).field(self, attr, val=None)__new__(subtype, shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, order='C') โ Create and return a new object. See help(type) for accurate signature.__dict__ โ dictionary for instance variables (if defined)The following methods are inherited from ndarray and are scalar methods identical to the corresponding array attribute. Please see ndarray for details.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__and__(self, value, /) โ Return self&value.__array__(...) โ a.__array__([dtype], /) -> reference if type unchanged, copy otherwise.__array_function__(...)__array_prepare__(...)__array_ufunc__(...)__array_wrap__(...)__bool__(self, /) โ True if self else False__complex__(...)__contains__(self, key, /) โ Return key in self.__copy__(...) โ a.__copy__() โ Used if copy.copy is called on an array. Returns a copy of the array. Equivalent to a.copy(order='K').__deepcopy__(...) โ a.__deepcopy__(memo, /) -> Deep copy of array.__delitem__(self, key, /) โ Delete self[key].__divmod__(self, value, /) โ Return divmod(self, value).__eq__(self, value, /) โ Return self==value.__float__(self, /) โ float(self)__floordiv__(self, value, /) โ Return self//value.__format__(...) โ Default object formatter.__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.__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. See numpy.all.any(...) โ a.any(axis=None, out=None, keepdims=False, *, where=True) โ Returns True if any of the elements of a evaluate to True. See numpy.any.argmax(...) โ a.argmax(axis=None, out=None) โ Return indices of the maximum values along the given axis. See numpy.argmax.argmin(...) โ a.argmin(axis=None, out=None) โ Return indices of the minimum values along the given axis. See numpy.argmin.argpartition(...) โ a.argpartition(kth, axis=-1, kind='introselect', order=None) โ Returns the indices that would partition this array. See numpy.argpartition.argsort(...) โ a.argsort(axis=-1, kind=None, order=None) โ Returns the indices that would sort this array. See numpy.argsort.astype(...) โ a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True) โ Copy of the array, cast to a specified type.byteswap(...) โ a.byteswap(inplace=False) โ Swap the bytes of the array elements.choose(...) โ a.choose(choices, out=None, mode='raise') โ Use an index array to construct a new array from a set of choices. See numpy.choose.clip(...) โ a.clip(min=None, max=None, out=None, **kwargs) โ Return an array whose values are limited to [min, max]. See numpy.clip.compress(...) โ a.compress(condition, axis=None, out=None) โ Return selected slices of this array along given axis. See numpy.compress.conj(...) โ a.conj() โ Complex-conjugate all elements. See numpy.conjugate.conjugate(...) โ a.conjugate() โ Return the complex conjugate, element-wise. See numpy.conjugate.copy(...) โ a.copy(order='C') โ Return a copy of the array.cumprod(...) โ a.cumprod(axis=None, dtype=None, out=None) โ Return the cumulative product of the elements along the given axis. See numpy.cumprod.cumsum(...) โ a.cumsum(axis=None, dtype=None, out=None) โ Return the cumulative sum of the elements along the given axis. See numpy.cumsum.diagonal(...) โ a.diagonal(offset=0, axis1=0, axis2=1) โ Return specified diagonals. See numpy.diagonal.dot(...) โ a.dot(b, out=None) โ Dot product of two arrays. See numpy.dot.dump(...) โ a.dump(file) โ Dump a pickle of the array to the specified file.dumps(...) โ a.dumps() โ Returns the pickle of the array as a string.fill(...) โ a.fill(value) โ Fill the array with a scalar value.flatten(...) โ a.flatten(order='C') โ Return a copy of the array collapsed into one dimension.getfield(...) โ a.getfield(dtype, offset=0) โ Returns a field of the given array as a certain type.item(...) โ a.item(*args) โ Copy an element of an array to a standard Python scalar and return it.itemset(...) โ a.itemset(*args) โ Insert scalar into an array.max(...) โ a.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True) โ Return the maximum along a given axis. See numpy.amax.mean(...) โ a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True) โ Returns the average of the array elements along given axis. See numpy.mean.min(...) โ a.min(axis=None, out=None, keepdims=False, initial=<no value>, where=True) โ Return the minimum along a given axis. See numpy.amin.newbyteorder(...) โ arr.newbyteorder(new_order='S', /) โ Return the array with the same data viewed with a different byte order.nonzero(...) โ a.nonzero() โ Return the indices of the elements that are non-zero. See numpy.nonzero.partition(...) โ a.partition(kth, axis=-1, kind='introselect', order=None) โ Rearranges the elements in the array.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. See numpy.prod.ptp(...) โ a.ptp(axis=None, out=None, keepdims=False) โ Peak to peak (maximum - minimum) value along a given axis. See numpy.ptp.put(...) โ a.put(indices, values, mode='raise') โ Set a.flat[n] = values[n] for all n in indices. See numpy.put.ravel(...) โ a.ravel([order]) โ Return a flattened array. See numpy.ravel.repeat(...) โ a.repeat(repeats, axis=None) โ Repeat elements of an array. See numpy.repeat.reshape(...) โ a.reshape(shape, order='C') โ Returns an array containing the same data with a new shape. See numpy.reshape.resize(...) โ a.resize(new_shape, refcheck=True) โ Change shape and size of array in-place.round(...) โ a.round(decimals=0, out=None) โ Return a with each element rounded to the given number of decimals. See numpy.around.searchsorted(...) โ a.searchsorted(v, side='left', sorter=None) โ Find indices where elements of v should be inserted in a to maintain order. See numpy.searchsorted.setfield(...) โ a.setfield(val, dtype, offset=0) โ Put a value into a specified place in a field defined by a data-type.setflags(...) โ a.setflags(write=None, align=None, uic=None) โ Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively.sort(...) โ a.sort(axis=-1, kind=None, order=None) โ Sort an array in-place. See numpy.sort.squeeze(...) โ a.squeeze(axis=None) โ Remove axes of length one from a. See numpy.squeeze.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. See numpy.std.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. See numpy.sum.swapaxes(...) โ a.swapaxes(axis1, axis2) โ Return a view of the array with axis1 and axis2 interchanged. See numpy.swapaxes.take(...) โ a.take(indices, axis=None, out=None, mode='raise') โ Return an array formed from the elements of a at the given indices. See numpy.take.tobytes(...) โ a.tobytes(order='C') โ Construct Python bytes containing the raw data bytes in the array.tofile(...) โ a.tofile(fid, sep="", format="%s") โ Write array to a file as text or binary (default).tolist(...) โ a.tolist() โ Return the array as an a.ndim-levels deep nested list of Python scalars.tostring(...) โ a.tostring(order='C') โ A compatibility alias for tobytes, with exactly the same behavior. (Deprecated since 1.19.0)trace(...) โ a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None) โ Return the sum along diagonals of the array. See numpy.trace.transpose(...) โ a.transpose(*axes) โ Returns a view of the array with axes transposed.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. See numpy.var.view(...) โ a.view([dtype][, type]) โ New view of array with the same data.T โ The transposed array. Same as self.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.ctypes โ An object to simplify the interaction of the array with the ctypes module.data โ Python buffer object pointing to the start of the array's data.dtype โ Data-type of the array's elements.flags โ Information about the memory layout of the array.flat โ A 1-D iterator over the array.imag โ The imaginary part of the array.itemsize โ Length of one array element in bytes.nbytes โ Total bytes consumed by the elements of the array.ndim โ Number of array dimensions.real โ The real part of the array.shape โ Tuple of array dimensions.size โ Number of elements in the array.strides โ Tuple of bytes to step in each dimension when traversing an array.__hash__ = Noneclass record(void)A data-type scalar that allows field access as attribute lookup.
recordvoidflexiblegenericbuiltins.object__getattribute__(self, attr) โ Return getattr(self, name).__getitem__(self, indx) โ Return self[key].__repr__(self) โ Return repr(self).__setattr__(self, attr, val) โ Implement setattr(self, name, value).__str__(self) โ Return str(self).pprint(self) โ Pretty-print all fields.__dict__ โ dictionary for instance variables (if defined)__weakref__ โ list of weak references to the object (if defined)__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.base โ base objectdtype โ dtype objectflags โ integer value of flagsThe following methods are scalar methods identical to the corresponding array attribute. Please see ndarray for details.
__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_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(...)any(...)argmax(...)argmin(...)argsort(...)astype(...)byteswap(...)choose(...)clip(...)compress(...)conj(...)conjugate(...)copy(...)cumprod(...)cumsum(...)diagonal(...)dump(...)dumps(...)fill(...)flatten(...)item(...)itemset(...)max(...)mean(...)min(...)newbyteorder(...) โ newbyteorder(new_order='S', /) โ Return a new dtype with a different byte order.nonzero(...)prod(...)ptp(...)put(...)ravel(...)repeat(...)reshape(...)resize(...)round(...)searchsorted(...)setflags(...)sort(...)squeeze(...)std(...)sum(...)swapaxes(...)take(...)tobytes(...)tofile(...)tolist(...)tostring(...)trace(...)transpose(...)var(...)view(...)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: structdata โ Pointer to start of data.flat โ A 1-D view of the scalar.imag โ The imaginary part of the scalar.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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 short = int16(signedinteger)Signed integer type, compatible with C short.
'h'numpy.shortnumpy.int16: 16-bit signed integer (-32_768 to 32_767).int16signedintegerintegernumbergenericbuiltins.object__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__and__(self, value, /) โ Return self&value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)denominator โ denominator of value (1)numerator โ numerator of value (the value itself)The following methods are scalar methods identical to the corresponding array attribute. Please see ndarray for details.
__array__(...) โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__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(...)any(...)argmax(...)argmin(...)argsort(...)astype(...)byteswap(...)choose(...)clip(...)compress(...)conj(...)conjugate(...)copy(...)cumprod(...)cumsum(...)diagonal(...)dump(...)dumps(...)fill(...)flatten(...)getfield(...)item(...)itemset(...)max(...)mean(...)min(...)newbyteorder(...) โ newbyteorder(new_order='S', /) โ Return a new dtype with a different byte order.nonzero(...)prod(...)ptp(...)put(...)ravel(...)repeat(...)reshape(...)resize(...)round(...)searchsorted(...)sort(...)squeeze(...)std(...)sum(...)swapaxes(...)take(...)tobytes(...)tofile(...)tolist(...)tostring(...)trace(...)transpose(...)var(...)view(...)Abstract base class of all NumPy scalar types.
newbyteorder(new_order='S', /) ๐ Return a new dtype with a different byte order. Changes are made in all fields and subโarrays. Options: 'S' (swap), '<'/'little', '>'/'big', '=' (native), '|'/'I' (ignore). Returns new_dtype : dtype.nonzero(...) ๐ Scalar method identical to ndarray.nonzero.prod(...) ๐ Scalar method identical to ndarray.prod.ptp(...) ๐ Scalar method identical to ndarray.ptp.put(...) ๐ Scalar method identical to ndarray.put.ravel(...) ๐ Scalar method identical to ndarray.ravel.repeat(...) ๐ Scalar method identical to ndarray.repeat.reshape(...) ๐ Scalar method identical to ndarray.reshape.resize(...) ๐ Scalar method identical to ndarray.resize.round(...) ๐ Scalar method identical to ndarray.round.searchsorted(...) ๐ Scalar method identical to ndarray.searchsorted.setfield(...) ๐ Scalar method identical to ndarray.setfield.setflags(...) ๐ Scalar method identical to ndarray.setflags.sort(...) ๐ Scalar method identical to ndarray.sort.squeeze(...) ๐ Scalar method identical to ndarray.squeeze.std(...) ๐ Scalar method identical to ndarray.std.sum(...) ๐ Scalar method identical to ndarray.sum.swapaxes(...) ๐ Scalar method identical to ndarray.swapaxes.take(...) ๐ Scalar method identical to ndarray.take.tobytes(...) โtofile(...) ๐ Scalar method identical to ndarray.tofile.tolist(...) ๐ Scalar method identical to ndarray.tolist.tostring(...) ๐ Scalar method identical to ndarray.tostring.trace(...) ๐ Scalar method identical to ndarray.trace.transpose(...) ๐ Scalar method identical to ndarray.transpose.var(...) ๐ Scalar method identical to ndarray.var.view(...) ๐ Scalar method identical to ndarray.view.T ๐ Scalar attribute identical to ndarray.T.__array_interface__ ๐ฆ Array protocol: Python side.__array_priority__ โ Array priority.__array_struct__ ๐ฆ Array protocol: struct.base ๐ Scalar attribute identical to ndarray.base.data ๐ Pointer to start of data.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.itemsize ๐ The length of one element in bytes.nbytes ๐ The length of the scalar in bytes.ndim ๐ง The number of array dimensions.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.__hash__ = None
signedintegerAbstract base class of all signed integer scalar types.
Method resolution order: signedinteger โ integer โ number โ generic โ builtins.object
integer:__round__(...)integer:denominator ๐ข denominator of value (1)numerator ๐ข numerator of value (the value itself)generic:All scalar methods identical to the corresponding array attribute. Includes: __abs__, __add__, __and__, __array__, __array_wrap__, __bool__, __copy__, __deepcopy__, __divmod__, __eq__, __float__, __floordiv__, __format__, __ge__, __getitem__, __gt__, __int__, __invert__, __le__, __lshift__, __lt__, __mod__, __mul__, __ne__, __neg__, __or__, __pos__, __pow__, __radd__, __rand__, __rdivmod__, __reduce__, __rfloordiv__, __rlshift__, __rmod__, __rmul__, __ror__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __setstate__, __sizeof__, __sub__, __truediv__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view.
generic:Same as listed in generic class above.
float32 (single precision)Singleโprecision floatingโpoint number type, compatible with C float.
Character code: 'f' Canonical name: numpy.single Alias on this platform: numpy.float32: 32โbitโprecision: sign bit, 8 bits exponent, 23 bits mantissa.
Method resolution order: float32 โ floating โ inexact โ number โ generic โ builtins.object
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False.__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() ๐ข Return a pair of integers whose ratio is exactly equal to the original floating point number. Raises OverflowError on infinities and ValueError on NaNs. Example: np.single(10.0).as_integer_ratio() โ (10, 1).__new__(*args, **kwargs) โ Create and return a new object.floating:__round__(...)generic:All scalar methods identical to the corresponding array attribute. Includes: __and__, __array__, __array_wrap__, __copy__, __deepcopy__, __format__, __getitem__, __invert__, __lshift__, __or__, __rand__, __reduce__, __rlshift__, __ror__, __rrshift__, __rshift__, __rxor__, __setstate__, __sizeof__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view.
generic:Same as listed in generic class above.
complex64 (singlecomplex)Complex number type composed of two singleโprecision floatingโpoint numbers.
Character code: 'F' Canonical name: numpy.csingle Alias: numpy.singlecomplex Alias on this platform: numpy.complex64: 2 ร 32โbit precision.
Method resolution order: complex64 โ complexfloating โ inexact โ number โ generic โ builtins.object
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__bool__(self, /) โ True if self else False.__complex__(...)__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.__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.__repr__(self, /) โ Return repr(self).__rfloordiv__(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.__new__(*args, **kwargs) โ Create and return a new object.complexfloating:__round__(...)generic:All scalar methods identical to the corresponding array attribute. Includes: __and__, __array__, __array_wrap__, __copy__, __deepcopy__, __divmod__, __format__, __getitem__, __invert__, __lshift__, __mod__, __or__, __rand__, __rdivmod__, __reduce__, __rlshift__, __rmod__, __ror__, __rrshift__, __rshift__, __rxor__, __setstate__, __sizeof__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view.
generic:Same as listed in generic class above.
str0 (str_)A unicode string. When used in arrays, this type strips trailing null codepoints. Unlike the builtin str, this supports the buffer protocol, exposing its contents as UCS4.
Character code: 'U' Alias: numpy.unicode_
Method resolution order: str_ โ builtins.str โ character โ flexible โ generic โ builtins.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).__new__(*args, **kwargs) โ Create and return a new object.builtins.str:All standard string methods: __add__, __contains__, __format__, __getattribute__, __getitem__, __getnewargs__, __iter__, __len__, __mod__, __mul__, __rmod__, __rmul__, __sizeof__, capitalize, casefold, center, count, encode, endswith, expandtabs, find, format, format_map, index, isalnum, isalpha, isascii, isdecimal, isdigit, isidentifier, islower, isnumeric, isprintable, isspace, istitle, isupper, join, ljust, lower, lstrip, partition, removeprefix, removesuffix, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill. Static method maketrans.
generic:All scalar methods identical to the corresponding array attribute. Includes: __abs__, __and__, __array__, __array_wrap__, __bool__, __copy__, __deepcopy__, __divmod__, __float__, __floordiv__, __int__, __invert__, __lshift__, __neg__, __or__, __pos__, __pow__, __radd__, __rand__, __rdivmod__, __reduce__, __rfloordiv__, __rlshift__, __ror__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __setstate__, __sub__, __truediv__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view.
generic:Same as listed in generic class above.
string_ (bytes_)A byte string. When used in arrays, this type strips trailing null bytes.
Character code: 'S' Alias: numpy.string_
Method resolution order: bytes_ โ builtins.bytes โ character โ flexible โ generic โ builtins.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).__new__(*args, **kwargs) โ Create and return a new object.builtins.bytes:All standard bytes methods: __add__, __contains__, __getattribute__, __getitem__, __getnewargs__, __iter__, __len__, __mod__, __mul__, __rmod__, __rmul__, capitalize, center, count, decode, endswith, expandtabs, find, hex, index, isalnum, isalpha, isascii, isdigit, islower, isspace, istitle, isupper, join, ljust, lower, lstrip, partition, removeprefix, removesuffix, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill.
generic:All scalar methods identical to the corresponding array attribute. Includes: __abs__, __and__, __array__, __array_wrap__, __bool__, __copy__, __deepcopy__, __divmod__, __float__, __floordiv__, __int__, __invert__, __lshift__, __neg__, __or__, __pos__, __pow__, __radd__, __rand__, __rdivmod__, __reduce__, __rfloordiv__, __rlshift__, __ror__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __setstate__, __sub__, __truediv__, __xor__, all, any, argmax, argmin, argsort, astype, byteswap, choose, clip, compress, conj, conjugate, copy, cumprod, cumsum, diagonal, dump, dumps, fill, flatten, getfield, item, itemset, max, mean, min, newbyteorder, nonzero, prod, ptp, put, ravel, repeat, reshape, resize, round, searchsorted, setfield, setflags, sort, squeeze, std, sum, swapaxes, take, tobytes, tofile, tolist, tostring, trace, transpose, var, view.
generic:Same as listed in generic class above.
Base class for all NumPy scalars.
translate(self, table, /, delete=b'') โ Return a copy with each character mapped by the given translation table.upper() โ Return a copy of B with all ASCII characters converted to uppercase.zfill(self, width, /) โ Pad a numeric string with zeros on the left.fromhex(string, /) โ Create a bytes object from a string of hexadecimal numbers.maketrans(frm, to, /) โ Return a translation table for bytes or bytearray translate method.__abs__(self, /) โ abs(self)__and__(self, value, /) โ Return self&value.__array__(...) โ Return 0-dim array from scalar with specified dtype.__array_wrap__(...) โ 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 ndarray.all.any(...) โ Scalar method identical to ndarray.any.argmax(...) โ Scalar method identical to ndarray.argmax.argmin(...) โ Scalar method identical to ndarray.argmin.argsort(...) โ Scalar method identical to ndarray.argsort.astype(...) โ Scalar method identical to ndarray.astype.byteswap(...) โ Scalar method identical to ndarray.byteswap.choose(...) โ Scalar method identical to ndarray.choose.clip(...) โ Scalar method identical to ndarray.clip.compress(...) โ Scalar method identical to ndarray.compress.conj(...)conjugate(...) โ Scalar method identical to ndarray.conjugate.copy(...) โ Scalar method identical to ndarray.copy.cumprod(...) โ Scalar method identical to ndarray.cumprod.cumsum(...) โ Scalar method identical to ndarray.cumsum.diagonal(...) โ Scalar method identical to ndarray.diagonal.dump(...) โ Scalar method identical to ndarray.dump.dumps(...) โ Scalar method identical to ndarray.dumps.fill(...) โ Scalar method identical to ndarray.fill.flatten(...) โ Scalar method identical to ndarray.flatten.getfield(...) โ Scalar method identical to ndarray.getfield.item(...) โ Scalar method identical to ndarray.item.itemset(...) โ Scalar method identical to ndarray.itemset.max(...) โ Scalar method identical to ndarray.max.mean(...) โ Scalar method identical to ndarray.mean.min(...) โ Scalar method identical to ndarray.min.newbyteorder(...) โ Return a new dtype with a different byte order.nonzero(...) โ Scalar method identical to ndarray.nonzero.prod(...) โ Scalar method identical to ndarray.prod.ptp(...) โ Scalar method identical to ndarray.ptp.put(...) โ Scalar method identical to ndarray.put.ravel(...) โ Scalar method identical to ndarray.ravel.repeat(...) โ Scalar method identical to ndarray.repeat.reshape(...) โ Scalar method identical to ndarray.reshape.resize(...) โ Scalar method identical to ndarray.resize.round(...) โ Scalar method identical to ndarray.round.searchsorted(...) โ Scalar method identical to ndarray.searchsorted.setfield(...) โ Scalar method identical to ndarray.setfield.setflags(...) โ Scalar method identical to ndarray.setflags.sort(...) โ Scalar method identical to ndarray.sort.squeeze(...) โ Scalar method identical to ndarray.squeeze.std(...) โ Scalar method identical to ndarray.std.sum(...) โ Scalar method identical to ndarray.sum.swapaxes(...) โ Scalar method identical to ndarray.swapaxes.take(...) โ Scalar method identical to ndarray.take.tobytes(...)tofile(...) โ Scalar method identical to ndarray.tofile.tolist(...) โ Scalar method identical to ndarray.tolist.tostring(...) โ Scalar method identical to ndarray.tostring.trace(...) โ Scalar method identical to ndarray.trace.transpose(...) โ Scalar method identical to ndarray.transpose.var(...) โ Scalar method identical to ndarray.var.view(...) โ Scalar method identical to ndarray.view.T โ Scalar attribute identical to ndarray.T.__array_interface__ โ Array protocol: Python side.__array_priority__ โ Array priority.__array_struct__ โ Array protocol: struct.base โ Scalar attribute identical to ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.A timedelta stored as a 64-bit integer. Character code: 'm'.
__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).__new__(*args, **kwargs) from builtins.type โ Create and return a new object.__round__(...)denominator โ denominator of value (1).numerator โ numerator of value (the value itself).All other methods and data descriptors are inherited from generic (see above).
Functions that operate element by element on whole arrays. Calling syntax: op(*x[, out], where=True, **kwargs).
__call__(self, /, *args, **kwargs) โ Call self as a function.__repr__(self, /) โ Return repr(self).__str__(self, /) โ Return str(self).accumulate(array, axis=0, dtype=None, out=None) โ Accumulate the result of applying the operator to all elements.at(a, indices, b=None, /) โ Performs unbuffered in place operation on operand 'a' for elements specified by 'indices'.outer(A, B, /, **kwargs) โ Apply the ufunc to all pairs (a, b) with a in A and b in B.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.reduceat(array, indices, axis=0, dtype=None, out=None) โ Performs a (local) reduce with specified slices over a single axis.identity โ The identity value.nargs โ The number of arguments.nin โ The number of inputs.nout โ The number of outputs.ntypes โ The number of numerical NumPy types.signature โ Definition of core elements for generalized ufunc.types โ Returns a list with types grouped input->output.Unsigned integer type, compatible with C unsigned char. Character code: 'B'. Range: 0 to 255.
__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__and__(self, value, /) โ Return self&value.__bool__(self, /) โ True if self else False.__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 suitable for use as an index.__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object.__round__(...)denominator โ denominator of value (1).numerator โ numerator of value (the value itself).All methods and data descriptors from generic are also inherited (see generic class above).
Unsigned integer type, compatible with C unsigned short. Character code: 'H'. Range: 0 to 65,535.
Identical to uint8 methods (same set of arithmetic and comparison operators).
Same as uint8 (inherits from integer and generic).
Unsigned integer type, compatible with C unsigned int. Character code: 'I'. Range: 0 to 4,294,967,295.
Identical to uint8 methods.
Same as uint8.
Unsigned integer type, compatible with C unsigned long. Character code: 'L'. Range: 0 to 18,446,744,073,709,551,615. Also aliased as uintp (unsigned integer large enough to fit a pointer).
Identical to uint8 methods.
Same as uint8.
Note: The classes uint8, uint16, uint32, and uint64 share the same set of methods inherited from unsignedinteger, integer, and generic. Only the character code, canonical name, and range differ.
The default value ('S') results in swapping the current byte order.
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.ptp โ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.tobytes โ (no description)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.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.Unsigned integer type, compatible with C unsigned long.
'L'numpy.uintnumpy.uint64: 64-bit unsigned integer (0 to 18_446_744_073_709_551_615).numpy.uintp: Unsigned integer large enough to fit pointer, compatible with C uintptr_t.uint64unsignedintegerintegernumbergenericbuiltins.object__abs__ โ abs(self)__add__ โ Return self+value.__and__ โ Return self&value.__bool__ โ True if self else False__divmod__ โ Return divmod(self, value).__eq__ โ Return self==value.__float__ โ float(self)__floordiv__ โ Return self//value.__ge__ โ Return self>=value.__gt__ โ Return self>value.__hash__ โ Return hash(self).__index__ โ Return self converted to an integer, if self is suitable for use as an index into a list.__int__ โ int(self)__invert__ โ ~self__le__ โ Return self<=value.__lshift__ โ Return self<<value.__lt__ โ Return self<value.__mod__ โ Return self%value.__mul__ โ Return self*value.__ne__ โ Return self!=value.__neg__ โ -self__or__ โ Return self|value.__pos__ โ +self__pow__ โ Return pow(self, value, mod).__radd__ โ Return value+self.__rand__ โ Return value&self.__rdivmod__ โ Return divmod(value, self).__repr__ โ Return repr(self).__rfloordiv__ โ Return value//self.__rlshift__ โ Return value<<self.__rmod__ โ Return value%self.__rmul__ โ Return value*self.__ror__ โ Return value|self.__rpow__ โ Return pow(value, self, mod).__rrshift__ โ Return value>>self.__rshift__ โ Return self>>value.__rsub__ โ Return value-self.__rtruediv__ โ Return value/self.__rxor__ โ Return value^self.__str__ โ Return str(self).__sub__ โ Return self-value.__truediv__ โ Return self/value.__xor__ โ Return self^value.__new__ โ Create and return a new object. See help(type) for accurate signature.__round__ โ (no description)denominator โ denominator of value (1)numerator โ numerator of value (the value itself)__array__ โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__array_wrap__ โ sc.__array_wrap__(obj) return scalar from array__copy__ โ (no description)__deepcopy__ โ (no description)__format__ โ NumPy array scalar formatter__getitem__ โ Return self[key].__reduce__ โ Helper for pickle.__setstate__ โ (no description)__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 โ (no description)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.itemset โ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.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. The new_order code can be any from the following: * 'S' - swap dtype from current to opposite endian * {'<', 'little'} - little endian * {'>', 'big'} - big endian * '=' - native order * {'|', 'I'} - ignore (no change to byte order). Parameters: new_order (str, optional) โ Byte order to force; a default value ('S') results in swapping the current byte order. Returns: new_dtype (dtype) โ New dtype object with the given change.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.ptp โ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.tobytes โ (no description)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.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.Unsigned integer type, compatible with C unsigned char.
'B'numpy.ubytenumpy.uint8: 8-bit unsigned integer (0 to 255).uint8unsignedintegerintegernumbergenericbuiltins.objectMethods, data descriptors, and inherited sections are identical to those of class uint64 above.
uint32, inherits from unsignedinteger)Unsigned integer type, compatible with C unsigned int.
'I'numpy.uintcnumpy.uint32: 32-bit unsigned integer (0 to 4_294_967_295).uint32unsignedintegerintegernumbergenericbuiltins.objectMethods, data descriptors, and inherited sections are identical to those of class uint64 above.
uint64, inherits from unsignedinteger)Unsigned integer type, compatible with C unsigned long.
'L'numpy.uintnumpy.uint64: 64-bit unsigned integer (0 to 18_446_744_073_709_551_615).numpy.uintp: Unsigned integer large enough to fit pointer, compatible with C uintptr_t.uint64unsignedintegerintegernumbergenericbuiltins.objectMethods, data descriptors, and inherited sections are identical to those of class uint64 above.
Signed integer type, compatible with C unsigned long long.
'Q'ulonglongunsignedintegerintegernumbergenericbuiltins.objectMethods, data descriptors, and inherited sections are identical to those of class uint64 above.
builtins.str and character)A unicode string. When used in arrays, this type strips trailing null codepoints. Unlike the builtin str, this supports the buffer protocol, 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'
'U'numpy.unicode_str_builtins.strcharacterflexiblegenericbuiltins.object__eq__ โ Return self==value.__ge__ โ Return self>=value.__gt__ โ Return self>value.__hash__ โ Return hash(self).__le__ โ Return self<=value.__lt__ โ Return self<value.__ne__ โ Return self!=value.__repr__ โ Return repr(self).__str__ โ Return str(self).__new__ โ Create and return a new object. See help(type) for accurate signature.__add__ โ Return self+value.__contains__ โ Return key in self.__format__ โ Return a formatted version of the string as described by format_spec.__getattribute__ โ Return getattr(self, name).__getitem__ โ Return self[key].__getnewargs__ โ (no description)__iter__ โ Implement iter(self).__len__ โ Return len(self).__mod__ โ Return self%value.__mul__ โ Return self*value.__rmod__ โ Return value%self.__rmul__ โ Return value*self.__sizeof__ โ Return the size of the string in memory, in bytes.capitalize โ Return a capitalized version of the string.casefold โ Return a version of the string suitable for caseless comparisons.center โ Return a centered string of length width.count โ S.count(sub[, start[, end]]) โ intencode โ Encode the string using the codec registered for encoding.endswith โ S.endswith(suffix[, start[, end]]) โ boolexpandtabs โ Return a copy where all tab characters are expanded using spaces.find โ S.find(sub[, start[, end]]) โ intformat โ S.format(*args, **kwargs) โ strformat_map โ S.format_map(mapping) โ strindex โ S.index(sub[, start[, end]]) โ intisalnum โ Return True if the string is an alpha-numeric string, False otherwise.isalpha โ Return True if the string is an alphabetic string, False otherwise.isascii โ Return True if all characters in the string are ASCII, False otherwise.isdecimal โ Return True if the string is a decimal string, False otherwise.isdigit โ Return True if the string is a digit string, False otherwise.isidentifier โ Return True if the string is a valid Python identifier, False otherwise.islower โ Return True if the string is a lowercase string, False otherwise.isnumeric โ Return True if the string is a numeric string, False otherwise.isprintable โ Return True if the string is printable, False otherwise.isspace โ Return True if the string is a whitespace string, False otherwise.istitle โ Return True if the string is a title-cased string, False otherwise.isupper โ Return True if the string is an uppercase string, False otherwise.join โ Concatenate any number of strings.ljust โ Return a left-justified string of length width.lower โ Return a copy of the string converted to lowercase.lstrip โ Return a copy of the string with leading whitespace removed.partition โ Partition the string into three parts using the given separator.removeprefix โ Return a str with the given prefix string removed if present.removesuffix โ Return a str with the given suffix string removed if present.replace โ Return a copy with all occurrences of substring old replaced by new.rfind โ S.rfind(sub[, start[, end]]) โ intrindex โ S.rindex(sub[, start[, end]]) โ intrjust โ Return a right-justified string of length width.rpartition โ Partition the string into three parts using the given separator.rsplit โ Return a list of the substrings in the string, using sep as the separator string.rstrip โ Return a copy of the string with trailing whitespace removed.split โ Return a list of the substrings in the string, using sep as the separator string.splitlines โ Return a list of the lines in the string, breaking at line boundaries.startswith โ S.startswith(prefix[, start[, end]]) โ boolstrip โ Return a copy of the string with leading and trailing whitespace removed.swapcase โ Convert uppercase characters to lowercase and lowercase characters to uppercase.title โ Return a version of the string where each word is titlecased.translate โ Replace each character in the string using the given translation table.upper โ Return a copy of the string converted to uppercase.zfill โ Pad a numeric string with zeros on the left, to fill a field of the given width.maketrans โ Return a translation table usable for str.translate().__abs__ โ abs(self)__and__ โ Return self&value.__array__ โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__array_wrap__ โ sc.__array_wrap__(obj) return scalar from array__bool__ โ True if self else False__copy__ โ (no description)__deepcopy__ โ (no description)__divmod__ โ Return divmod(self, value).__float__ โ float(self)__floordiv__ โ Return self//value.__int__ โ int(self)__invert__ โ ~self__lshift__ โ Return self<<value.__neg__ โ -self__or__ โ Return self|value.__pos__ โ +self__pow__ โ Return pow(self, value, mod).__radd__ โ Return value+self.__rand__ โ Return value&self.__rdivmod__ โ Return divmod(value, self).__reduce__ โ Helper for pickle.__rfloordiv__ โ Return value//self.__rlshift__ โ Return value<<self.__ror__ โ Return value|self.__rpow__ โ Return pow(value, self, mod).__rrshift__ โ Return value>>self.__rshift__ โ Return self>>value.__rsub__ โ Return value-self.__rtruediv__ โ Return value/self.__rxor__ โ Return value^self.__setstate__ โ (no description)__sub__ โ Return self-value.__truediv__ โ Return self/value.__xor__ โ 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 โ (no description)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.itemset โ Scalar method identical to the corresponding array attribute. Please see ndarray.itemset.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.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. The new_order code can be any from the following: * 'S' - swap dtype from current to opposite endian * {'<', 'little'} - little endian * {'>', 'big'} - big endian * '=' - native order * {'|', 'I'} - ignore (no change to byte order). Parameters: new_order (str, optional) โ Byte order to force; a default value ('S') results in swapping the current byte order. Returns: new_dtype (dtype) โ New dtype object with the given change.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.ptp โ Scalar method identical to the corresponding array attribute. Please see ndarray.ptp.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.tobytes โ (no description)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.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.Abstract base class of all unsigned integer scalar types.
unsignedintegerintegernumbergenericbuiltins.objectMethods, data descriptors, and inherited sections are identical to those of class uint64 above.
ushort = class uint16(unsignedinteger)Unsigned integer type, compatible with C unsigned short.
๐งฌ Character code: 'H'
๐ท๏ธ Canonical name: numpy.ushort
๐ Alias on this platform (Linux x86_64): numpy.uint16: 16-bit unsigned integer (0 to 65_535).
uint16unsignedintegerintegernumbergenericbuiltins.object__abs__(self, /) โ abs(self)__add__(self, value, /) โ Return self+value.__and__(self, value, /) โ Return self&value.__bool__(self, /) โ True if self else False__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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.__round__(...)denominator โ denominator of value (1)numerator โ numerator of value (the value itself)__array__(...) โ sc.__array__(dtype) return 0-dim array from scalar with specified dtype__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(...) โ Please see ndarray.all.any(...) โ Please see ndarray.any.argmax(...) โ Please see ndarray.argmax.argmin(...) โ Please see ndarray.argmin.argsort(...) โ Please see ndarray.argsort.astype(...) โ Please see ndarray.astype.byteswap(...) โ Please see ndarray.byteswap.choose(...) โ Please see ndarray.choose.clip(...) โ Please see ndarray.clip.compress(...) โ Please see ndarray.compress.conj(...)conjugate(...) โ Please see ndarray.conjugate.copy(...) โ Please see ndarray.copy.cumprod(...) โ Please see ndarray.cumprod.cumsum(...) โ Please see ndarray.cumsum.diagonal(...) โ Please see ndarray.diagonal.dump(...) โ Please see ndarray.dump.dumps(...) โ Please see ndarray.dumps.fill(...) โ Please see ndarray.fill.flatten(...) โ Please see ndarray.flatten.getfield(...) โ Please see ndarray.getfield.item(...) โ Please see ndarray.item.itemset(...) โ Please see ndarray.itemset.max(...) โ Please see ndarray.max.mean(...) โ Please see ndarray.mean.min(...) โ Please see ndarray.min.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. The new_order code can be any from the following: new_order : str, optional โ Byte order to force; default ('S') swaps current byte order. Returns: new_dtype : dtype โ New dtype object.nonzero(...) โ Please see ndarray.nonzero.prod(...) โ Please see ndarray.prod.ptp(...) โ Please see ndarray.ptp.put(...) โ Please see ndarray.put.ravel(...) โ Please see ndarray.ravel.repeat(...) โ Please see ndarray.repeat.reshape(...) โ Please see ndarray.reshape.resize(...) โ Please see ndarray.resize.round(...) โ Please see ndarray.round.searchsorted(...) โ Please see ndarray.searchsorted.setfield(...) โ Please see ndarray.setfield.setflags(...) โ Please see ndarray.setflags.sort(...) โ Please see ndarray.sort.squeeze(...) โ Please see ndarray.squeeze.std(...) โ Please see ndarray.std.sum(...) โ Please see ndarray.sum.swapaxes(...) โ Please see ndarray.swapaxes.take(...) โ Please see ndarray.take.tobytes(...)tofile(...) โ Please see ndarray.tofile.tolist(...) โ Please see ndarray.tolist.tostring(...) โ Please see ndarray.tostring.trace(...) โ Please see ndarray.trace.transpose(...) โ Please see ndarray.transpose.var(...) โ Please see ndarray.var.view(...) โ Please see ndarray.view.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: structbase โ Scalar attribute identical to the corresponding array attribute. Please see ndarray.base.data โ Pointer to start of data.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.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.__hash__ = Nonevectorize = class vectorize(builtins.object)vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None)
Generalized function class.
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.
pyfunc : callable โ A python function or method.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. (Version added: 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. (Version added: 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. (Version added: 1.12.0)vectorized : callable โ Vectorized function.frompyfunc โ Takes an arbitrary Python function and returns a ufuncThe 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.
.. [1] :doc:`/reference/c-api/generalized-ufuncs`
>>> 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.]])
__call__(self, *args, **kwargs) โ Return arrays with the results of pyfunc broadcast (vectorized) over args and kwargs not in excluded.__init__(self, pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None) โ Initialize self. See help(type(self)) for accurate signature.__dict__ โ dictionary for instance variables (if defined)__weakref__ โ list of weak references to the object (if defined)void = class void(flexible)Either an opaque sequence of bytes, or a structure.
>>> np.void(b'abcd')
void(b'\x61\x62\x63\x64')
Structured void scalars can only be constructed via extraction from structured_arrays:
>>> arr = np.array((1, 2), dtype=[('x', np.int8), ('y', np.int8)])
>>> arr[()]
(1, 2) # looks like a tuple, but is `np.void`
๐งฌ Character code: 'V'
voidflexiblegenericbuiltins.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.__new__(*args, **kwargs) from builtins.type โ Create and return a new object. See help(type) for accurate signature.base โ base objectdtype โ dtype objectflags โ integer value of flags__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_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(...) โ Please see ndarray.all.any(...) โ Please see ndarray.any.argmax(...) โ Please see ndarray.argmax.argmin(...) โ Please see ndarray.argmin.argsort(...) โ Please see ndarray.argsort.astype(...) โ Please see ndarray.astype.byteswap(...) โ Please see ndarray.byteswap.choose(...) โ Please see ndarray.choose.clip(...) โ Please see ndarray.clip.compress(...) โ Please see ndarray.compress.conj(...)conjugate(...) โ Please see ndarray.conjugate.copy(...) โ Please see ndarray.copy.cumprod(...) โ Please see ndarray.cumprod.cumsum(...) โ Please see ndarray.cumsum.diagonal(...) โ Please see ndarray.diagonal.dump(...) โ Please see ndarray.dump.dumps(...) โ Please see ndarray.dumps.fill(...) โ Please see ndarray.fill.flatten(...) โ Please see ndarray.flatten.item(...) โ Please see ndarray.item.itemset(...) โ Please see ndarray.itemset.max(...) โ Please see ndarray.max.mean(...) โ Please see ndarray.mean.min(...) โ Please see ndarray.min.newbyteorder(...) โ newbyteorder(new_order='S', /) โ Return a new dtype with a different byte order. (Same as above)nonzero(...) โ Please see ndarray.nonzero.prod(...) โ Please see ndarray.prod.ptp(...) โ Please see ndarray.ptp.put(...) โ Please see ndarray.put.ravel(...) โ Please see ndarray.ravel.repeat(...) โ Please see ndarray.repeat.reshape(...) โ Please see ndarray.reshape.resize(...) โ Please see ndarray.resize.round(...) โ Please see ndarray.round.searchsorted(...) โ Please see ndarray.searchsorted.setflags(...) โ Please see ndarray.setflags.sort(...) โ Please see ndarray.sort.squeeze(...) โ Please see ndarray.squeeze.std(...) โ Please see ndarray.std.sum(...) โ Please see ndarray.sum.swapaxes(...) โ Please see ndarray.swapaxes.take(...) โ Please see ndarray.take.tobytes(...)tofile(...) โ Please see ndarray.tofile.tolist(...) โ Please see ndarray.tolist.tostring(...) โ Please see ndarray.tostring.trace(...) โ Please see ndarray.trace.transpose(...) โ Please see ndarray.transpose.var(...) โ Please see ndarray.var.view(...) โ Please see ndarray.view.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: structdata โ Pointer to start of data.flat โ A 1-D view of the scalar.imag โ The imaginary part of the scalar.itemsize โ The length of one element in bytes.nbytes โ The length of the scalar in bytes.ndim โ The number of array dimensions.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.void0 = class void(flexible)Alias for void class. Identical in every respect. See void class above for full details.
__dir__()__getattr__(attr)# module level getattr is only supported in 3.7 onwards
https://www.python.org/dev/peps/pep-0562/
_add_newdoc_ufunc(...)add_ufunc_docstring(ufunc, new_docstring)
Replace the docstring for a ufunc with new_docstring. This method will only work if the current docstring for the ufunc is NULL. (At the C level, i.e. when ufunc->doc is NULL.)
This method allocates memory for new_docstring on the heap. Technically this creates a memory leak, since this memory will not be reclaimed until the end of the program even if the ufunc itself is removed. However this will only be a problem if the user is repeatedly creating ufuncs with no documentation, adding documentation via add_newdoc_ufunc, and then throwing away the ufunc.
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.
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), ...].UserWarning if this is used to attach documentation to a pure-python object.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:
PyTypeObject after calling PyType_ReadyPy_INCREF on the str and losing the reference, so the str will never be releasedIf possible it should be avoided.
add_newdoc_ufunc = _add_newdoc_ufunc(...)Same as _add_newdoc_ufunc.
alen(a)Return the length of the first dimension of the input array.
.. deprecated:: 1.18
numpy.alen is deprecated, use len instead.
a.shape, size>>> a = np.zeros((7,4,5))
>>> a.shape[0]
7
>>> np.alen(a)
7
all(a, axis=None, out=None, keepdims=<no value>, *, where=<no value>)Test whether all array elements along a given axis evaluate to True.
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.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 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.True values. See ~numpy.ufunc.reduce for details. .. versionadded:: 1.20.0out is specified, in which case a reference to out is returned.ndarray.all : equivalent methodany : Test whether any element along a given axis evaluates to True.Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.
>>> 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
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. 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.
a will be considered equal to NaN's in b in the output array. .. versionadded:: 1.10.0isclose, all, any, equalIf 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 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.
>>> 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
alltrue(*args, **kwargs)Check if all elements of input array are true.
numpy.all : Equivalent function; see for details.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.
ufuncs-output-type for more details.keepdims will not be passed through to the amax 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.~numpy.ufunc.reduce for details. .. versionadded:: 1.15.0~numpy.ufunc.reduce for details. .. versionadded:: 1.17.0a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.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, fminNaN 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 amax for element-wise comparison of 2 arrays; when a.shape[0] is 2, maximum(a[0], a[1]) is faster than amax(a, axis=0).
>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
[2, 3]])
>>> np.amax(a) # Maximum of the flattened array
3
>>> np.amax(a, axis=0) # Maxima along the first axis
array([2, 3])
>>> np.amax(a, axis=1) # Maxima along the second axis
array([1, 3])
>>> np.amax(a, where=[False, True], initial=-1, axis=0)
array([-1, 3])
>>> b = np.arange(5, dtype=float)
>>> b[2] = np.NaN
>>> np.amax(b)
nan
>>> np.amax(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
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.
ufuncs-output-type for more details.keepdims will not be passed through to the amin 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.~numpy.ufunc.reduce for details. .. versionadded:: 1.15.0~numpy.ufunc.reduce for details. .. versionadded:: 1.17.0a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.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, fmaxNaN 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 amin for element-wise comparison of 2 arrays; when a.shape[0] is 2, minimum(a[0], a[1]) is faster than amin(a, axis=0).
>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
[2, 3]])
>>> np.amin(a) # Minimum of the flattened array
0
>>> np.amin(a, axis=0) # Minima along the first axis
array([0, 1])
>>> np.amin(a, axis=1) # Minima along the second axis
array([0, 2])
>>> np.amin(a, where=[False, True], initial=10, axis=0)
array([10, 1])
>>> b = np.arange(5, dtype=float)
>>> b[2] = np.NaN
>>> np.amin(b)
nan
>>> np.amin(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
angle(z, deg=False)Return the angle of the complex argument.
(-pi, pi], with dtype as numpy.float64. .. versionchanged:: 1.16.0 This function works on subclasses of ndarray like ma.array.arctan2absoluteAlthough the angle of the complex number 0 is undefined, numpy.angle(0) returns the value 0.
>>> 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
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 unless axis is not None.
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.a). See :ref:ufuncs-output-type for more details.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.True values. See ~numpy.ufunc.reduce for details. .. versionadded:: 1.20.0ndarray is returned unless out is specified, in which case a reference to out is returned.ndarray.any : equivalent methodall : Test whether all elements along a given axis evaluate to True.Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.
>>> np.any([[True, False], [True, True]])
True
>>> np.any([[True, False], [False, False]], axis=0)
array([ True, False])
>>> np.any([-1, 0, 5])
True
>>> np.any(np.nan)
True
>>> np.any([[True, False], [False, False]], where=[[False], [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)
append(arr, values, axis=None)Append values to the end of an array.
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.values are appended. If axis is not given, both arr and values are flattened before use.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.insert : Insert elements into an array.delete : Delete elements from an array.>>> 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)
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])
arr along the specified axis.arr is sliced.func1d.func1d. .. versionadded:: 1.9.0out 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.apply_over_axes : Apply a function repeatedly over multiple axes.>>> 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.
func(a, axis).func is applied; the elements must be integers.a, but the shape can be different. This depends on whether func changes the shape of its output with respect to its input.apply_along_axis : Apply a function to 1-D slices of an array along the given axis.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.
>>> 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]]])
arange(...)arange([start,] stop[, step,], dtype=None, *, like=None)
Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases.
step is not an integer and floating point round-off affects the length of out.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 is not given, infer the data type from the other input arguments.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.0ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.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.>>> 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])
argmax(a, axis=None, out=None)Returns the indices of the maximum values along an axis.
a.shape with the dimension along axis removed.ndarray.argmax, argminamax : 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.In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.
>>> 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.max(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.max(x, axis=-1)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
array([4, 3])
argmin(a, axis=None, out=None)Returns the indices of the minimum values along an axis.
a.shape with the dimension along axis removed.ndarray.argmin, argmaxamin : 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.In case of multiple occurrences of the minimum values, the indices corresponding to the first occurrence are returned.
>>> 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.min(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.max(x, axis=-1)
>>> np.take_along_axis(x, np.expand_dims(index_array, axis=-1), axis=-1).squeeze(axis=-1)
array([2, 0])
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
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.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=a) always yields the partitioned a, irrespective of dimensionality.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.See partition for notes on the different selection algorithms.
One dimensional array:
>>> x = np.array([3, 4, 2, 1])
>>> x[np.argpartition(x, 3)]
array([2, 1, 3, 4])
>>> x[np.argpartition(x, (1, 3))]
array([1, 2, 3, 4])
>>> x = [3, 4, 2, 1]
>>> np.array(x)[np.argpartition(x, 3)]
array([2, 1, 3, 4])
Multi-dimensional array:
>>> x = np.array([[3, 4, 2], [1, 3, 1]])
>>> index_array = np.argpartition(x, kth=1, axis=-1)
>>> np.take_along_axis(x, index_array, axis=-1) # same as np.partition(x, kth=1)
array([[2, 3, 4],
[1, 1, 3]])
argsort(a, axis=-1, kind=None, order=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.
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.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.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.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.
One dimensional array:
>>> 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])
argwhere(a)Find the indices of array elements that are non-zero, grouped by element.
(N, a.ndim) where N is the number of non-zero items.where, nonzeronp.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.
>>> 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]])
around(a, decimals=0, out=None)Evenly round to the given number of decimals.
ufuncs-output-type for more details.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.ndarray.round : equivalent methodceil, fix, floor, rint, truncFor 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.around 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)
>>> np.around([0.37, 1.64])
array([0., 2.])
>>> np.around([0.37, 1.64], decimals=1)
array([0.4, 1.6])
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([0., 2., 2., 4., 4.])
>>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
array([ 1, 2, 3, 11])
>>> np.around([1,2,3,11], decimals=-1)
array([ 0, 0, 0, 10])
array(...)array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)
Create an array.
dtype, order, etc.).| 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 |
copy=False 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'.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.0empty_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.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.
>>> 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.mat('1 2; 3 4'))
array([[1, 2],
[3, 4]])
>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
[3, 4]])
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.
max_line_width. Defaults to numpy.get_printoptions()['linewidth'].numpy.get_printoptions()['precision'].numpy.get_printoptions()['suppress'].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.numpy.get_printoptions()['threshold'].numpy.get_printoptions()['edgeitems'].numpy.get_printoptions()['sign'].precision option for floating-point types. Defaults to numpy.get_printoptions()['floatmode']. Can take values: 'fixed', 'unique', 'maxprec', 'maxprec_equal'.False, optional'1.13' enables 1.13 legacy printing mode. If set to False, disables legacy mode. .. versionadded:: 1.14.0formatter does not return a string.array_str, array_repr, set_printoptions, get_printoptionsIf 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.
>>> 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]'
array_equal(a1, a2, equal_nan=False)True if two arrays have the same shape and elements, False otherwise.
nan. .. versionadded:: 1.19.0allclose: 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.>>> 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
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.
>>> 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
array_repr(arr, max_line_width=None, precision=None, suppress_small=None)Return the string representation of an array.
max_line_width. Defaults to numpy.get_printoptions()['linewidth'].numpy.get_printoptions()['precision'].numpy.get_printoptions()['suppress'].array_str, array2string, set_printoptions>>> 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. ])'
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.
split : Split array into multiple sub-arrays of equal size.>>> 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])]
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.
max_line_width. Defaults to numpy.get_printoptions()['linewidth'].numpy.get_printoptions()['precision'].numpy.get_printoptions()['suppress'].array2string, array_repr, set_printoptions>>> np.array_str(np.arange(3))
'[0 1 2]'
asanyarray(...)asanyarray(a, dtype=None, order=None, *, like=None)
Convert the input to an ndarray, but pass ndarray subclasses through.
a is Fortran contiguous, 'C' otherwise. 'K' (keep) preserve input order. Defaults to 'C'.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.0a. If a is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed.asarray : Similar function which always returns ndarrays.ascontiguousarray : Convert input to a contiguous array.asfarray : Convert input to a floating point ndarray.asfortranarray : Convert input to an ndarray with column-major memory order.asarray_chkfinite : Similar function which checks input for NaNs and Infs.fromiter : Create an array from an iterator.fromfunction : Construct an array by executing a function on grid positions.Convert a list into an array:
>>> a = [1, 2]
>>> np.asanyarray(a)
array([1, 2])
Instances of `ndarray` subclasses are passed through as-is:
>>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
>>> np.asanyarray(a) is a
True
asarray(...)asarray(a, dtype=None, order=None, *, like=None)
Convert the input to an array.
a is Fortran contiguous, 'C' otherwise. 'K' (keep) preserve input order. Defaults to 'C'.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.0a. 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.asanyarray : Similar function which passes through subclasses.ascontiguousarray : Convert input to a contiguous array.asfarray : Convert input to a floating point ndarray.asfortranarray : Convert input to an ndarray with column-major memory order.asarray_chkfinite : Similar function which checks input for NaNs and Infs.fromiter : Create an array from an iterator.fromfunction : Construct an array by executing a function on grid positions.Convert a list into an array:
>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])
Existing arrays are not copied:
>>> a = np.array([1, 2])
>>> np.asarray(a) is a
True
If `dtype` is set, array is copied only if dtype does not match:
>>> a = np.array([1, 2], dtype=np.float32)
>>> np.asarray(a, dtype=np.float32) is a
True
>>> np.asarray(a, dtype=np.float64) is a
False
Contrary to `asanyarray`, ndarray subclasses are not passed through:
>>> issubclass(np.recarray, np.ndarray)
True
>>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray)
>>> np.asarray(a) is a
False
>>> np.asanyarray(a) is a
True
asarray_chkfinite(a, dtype=None, order=None)Convert the input to an array, checking for NaNs or Infs.
a is Fortran contiguous, 'C' otherwise. 'K' (keep) preserve input order. Defaults to 'C'.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.a contains NaN (Not a Number) or Inf (Infinity).asarray : Create and array.asanyarray : Similar function which passes through subclasses.ascontiguousarray : Convert input to a contiguous array.asfarray : Convert input to a floating point ndarray.asfortranarray : Convert input to an ndarray with column-major memory order.fromiter : Create an array from an iterator.fromfunction : Construct an array by executing a function on grid positions.Convert a list into an array. If all elements are finite
``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
ascontiguousarray(...)ascontiguousarray(a, dtype=None, *, like=None)
Return a contiguous array (ndim >= 1) in memory (C order).
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.0a, with type dtype if specified.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.>>> x = np.arange(6).reshape(2,3)
>>> np.ascontiguousarray(x, dtype=np.float32)
array([[0., 1., 2.],
[3., 4., 5.]], dtype=float32)
>>> x.flags['C_CONTIGUOUS']
True
Note: This function returns an array with at least one-dimension (1-d)
so it will not preserve 0-d arrays.
asfarray(a, dtype=<class 'numpy.float64'>)Return an array converted to a float type.
a. If dtype is one of the 'int' dtypes, it is replaced with float64.a as a float ndarray.>>> np.asfarray([2, 3])
array([2., 3.])
>>> np.asfarray([2, 3], dtype='float')
array([2., 3.])
>>> np.asfarray([2, 3], dtype='int8')
array([2., 3.])
asfortranarray(...)asfortranarray(a, dtype=None, *, like=None)
Return an array (ndim >= 1) laid out in Fortran order in memory.
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.0a in Fortran, or column-major, order.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.>>> x = np.arange(6).reshape(2,3)
>>> y = np.asfortranarray(x)
>>> x.flags['F_CONTIGUOUS']
False
>>> y.flags['F_CONTIGUOUS']
True
Note: This function returns an array with at least one-dimension (1-d)
so it will not preserve 0-d arrays.
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).
data interpreted as a matrix.>>> x = np.array([[1, 2], [3, 4]])
>>> m = np.asmatrix(x)
>>> x[0,0] = 5
>>> m
matrix([[5, 2],
[3, 4]])
asscalar(a)Convert an array of size 1 to its scalar equivalent.
.. deprecated:: 1.16
Deprecated, use numpy.ndarray.item() instead.
a. The output data type is the same type returned by the input's item method.>>> np.asscalar(np.array([24]))
24
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.
a.ndim >= 1. Copies are made only if necessary.atleast_2d, atleast_3d>>> 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])]
atleast_2d(*arys)View inputs as arrays with at least two dimensions.
a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.atleast_1d, atleast_3d>>> 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]])]
atleast_3d(*arys)View inputs as arrays with at least three dimensions.
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).atleast_1d, atleast_2d>>> 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)
average(a, axis=None, weights=None, returned=False)Compute the weighted average along the specified axis.
a is not an array, a conversion is attempted.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.a. Each value in a contributes to the average 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. The 1-D calculation is: avg = sum(a * weights) / sum(weights). The only constraint on weights is that sum(weights) must not be 0.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.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.numpy.ma.average for a version robust to this type of error.weights is not the same as the shape of a along axis.meanma.average : average for masked arrays -- useful if your data contains "missing" valuesnumpy.result_type : Returns the type that results from applying the numpy type promotion rules to the arguments.>>> 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.
>>> a = np.ones(5, dtype=np.float128)
>>> w = np.ones(5, dtype=np.complex64)
>>> avg = np.average(a, weights=w)
>>> print(avg.dtype)
complex256
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.
blackman, hamming, hanning, kaiserThe Bartlett window is defined as
w(n) = 2/(M-1) * ( (M-1)/2 - |n - (M-1)/2| )
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 is the product of two sinc functions. Note the excellent discussion in Kanasewich.
>>> 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):
>>> from numpy.fft import fft, fftshift
>>> window = np.bartlett(51)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Bartlett window")
Text(0.5, 1.0, 'Bartlett window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
>>> plt.figure()
<Figure size 640x480 with 0 Axes>
>>> 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)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Bartlett window")
Text(0.5, 1.0, 'Frequency response of Bartlett window')
>>> plt.ylabel("Magnitude [dB]")
Text(0, 0.5, 'Magnitude [dB]')
>>> plt.xlabel("Normalized frequency [cycles per sample]")
Text(0.5, 0, 'Normalized frequency [cycles per sample]')
>>> _ = plt.axis('tight')
>>> plt.show()
base_repr(number, base=2, padding=0)Return a string representation of a number in the given base system.
number to the base number system. The valid range is 2-36, the default value is 2.number in base system.binary_repr : Faster version of base_repr for base 2.>>> 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'
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 -2^(N-1) to +2^(N-1)-1.
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, it will be ignored, and num will be returned in binary (num > 0) or two's complement (num < 0) form with its width equal to the minimum number of bits needed to represent the number in the designated form. This behavior is deprecated and will later raise an error. .. deprecated:: 1.12.0num or two's complement of num.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.binary_repr is equivalent to using base_repr with base 2, but about 25x faster.
>>> 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'
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.
x.out is equal to np.amax(x)+1.minlength is negative.histogram, digitize, unique>>> 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])
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.
bartlett, hamming, hanning, kaiserThe Blackman window is defined as
w(n) = 0.42 - 0.5 cos(2ฯn/M) + 0.08 cos(4ฯ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.
>>> 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:
>>> from numpy.fft import fft, fftshift
>>> window = np.blackman(51)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Blackman window")
Text(0.5, 1.0, 'Blackman window')
>>> plt.ylabel("Amplitude")
Text(0, 0.5, 'Amplitude')
>>> plt.xlabel("Sample")
Text(0.5, 0, 'Sample')
>>> plt.show()
>>> plt.figure()
<Figure size 640x480 with 0 Axes>
>>> 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)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Blackman window")
Text(0.5, 1.0, 'Frequency response of Blackman window')
>>> plt.ylabel("Magnitude [dB]")
Text(0, 0.5, 'Magnitude [dB]')
>>> plt.xlabel("Normalized frequency [cycles per sample]")
Text(0.5, 0, 'Normalized frequency [cycles per sample]')
>>> _ = plt.axis('tight')
>>> plt.show()
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
[[a, b], c] is illegal, and should be spelt [[a, b], [c]][[a, b], []]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).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, ...]]).
The most common use of this function is to build a block matrix
>>> 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 places 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]])
bmat(obj, ldict=None, gdict=None)Build a matrix object from a string, nested sequence, or array.
obj is not a string or gdict is None.obj is not a string.block : A generalization of this function for N-d arrays, that returns normal ndarrays.>>> A = np.mat('1 1; 1 1')
>>> B = np.mat('2 2; 2 2')
>>> C = np.mat('3 4; 5 6')
>>> D = np.mat('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]])
broadcast_arrays(*args, subok=False)Broadcast any number of arrays against each other.
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.broadcastbroadcast_tobroadcast_shapes>>> 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]])]
broadcast_shapes(*args)Broadcast the input shapes into a single shape.
:ref:Learn more about broadcasting here <basics.broadcasting>.
.. versionadded:: 1.20.0
broadcastbroadcast_arraysbroadcast_to>>> 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)
broadcast_to(array, shape, subok=False)Broadcast an array to a new shape.
broadcastbroadcast_arraysbroadcast_shapes.. versionadded:: 1.10.0
>>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
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
busdaycalendar object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided.begindates and enddates together, containing the number of valid days between the begin and end dates.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.>>> # 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
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
dates.busdaycalendar object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided.dates and offsets together, containing the dates with offsets applied.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.>>> # First business day in October 2011 (not accounting for holidays)
... np.busday_offset('2011-10', 0, roll='forward')
numpy.datetime64('2011-10-03')
>>> # Last business day in February 2012 (not accounting for holidays)
... np.busday_offset('2012-03', -1, roll='forward')
numpy.datetime64('2012-02-29')
>>> # Third Wednesday in January 2011
... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed')
numpy.datetime64('2011-01-19')
>>> # 2012 Mother's Day in Canada and the U.S.
... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun')
numpy.datetime64('2012-05-13')
>>> # First business day on or after a date
... np.busday_offset('2011-03-20', 0, roll='forward')
numpy.datetime64('2011-03-21')
>>> np.busday_offset('2011-03-22', 0, roll='forward')
numpy.datetime64('2011-03-22')
>>> # First business day after a date
... np.busday_offset('2011-03-20', 1, roll='backward')
numpy.datetime64('2011-03-21')
>>> np.busday_offset('2011-03-22', 1, roll='backward')
numpy.datetime64('2011-03-23')
byte_bounds(a)Returns pointers to the end-points of an array.
a is not contiguous it will not use every byte between the (low, high) values.>>> I = np.eye(2, dtype='f'); I.dtype
dtype('float32')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True
>>> I = np.eye(2); I.dtype
dtype('float64')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True
can_cast(...)can_cast(from_, to, casting='safe')
Returns True if cast between data types can occur according to the casting rule. If from is a scalar or array scalar, also returns True if the scalar value can be cast without overflow or truncation to an integer.
.. 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.
dtype, result_typeBasic examples
>>> 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
Casting scalars
>>> np.can_cast(100, 'i1')
True
>>> np.can_cast(150, 'i1')
False
>>> np.can_cast(150, 'u1')
True
>>> np.can_cast(3.5e100, np.float32)
False
>>> np.can_cast(1000.0, np.float32)
True
Array scalar checks the value, array does not
>>> np.can_cast(np.array(1000.0), np.float32)
True
>>> np.can_cast(np.array([1000.0]), np.float32)
False
Using the casting rules
>>> np.can_cast('i8', 'i8', 'no')
True
>>> np.can_cast('<i8', '>i8', 'no')
False
>>> np.can_cast('<i8', '>i8', 'equiv')
True
>>> np.can_cast('<i4', '>i8', 'equiv')
False
>>> np.can_cast('<i4', '>i8', 'safe')
True
>>> np.can_cast('<i8', '>i4', 'safe')
False
>>> np.can_cast('<i8', '>i4', 'same_kind')
True
>>> np.can_cast('<i8', '>u4', 'same_kind')
False
>>> np.can_cast('<i8', '>u4', 'unsafe')
True
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:
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;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;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.[0, n-1], where n is the number of choices, unless mode=wrap or mode=clip, in which cases any integers are permissible.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 is always buffered if mode='raise'; use other modes for better performance.[0, n-1] will be treated: na and each choice array are not all broadcastable to the same shape.ndarray.choose : equivalent methodnumpy.take_along_axis : Preferable if choices is an arrayTo 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.
>>> 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 = [[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]]])
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.
None, clipping is not performed on the corresponding edge. Only one of a_min and a_max may be None. Both are broadcast against a.out must be of the right shape to hold the output. Its type is preserved... versionadded:: 1.17.0
a, but where values < a_min are replaced with a_min, and those > a_max with a_max.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.
>>> 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])
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.
stack, hstack, vstack, concatenate>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
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.
dtype, mintypecode>>> 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'>
Performs element-wise comparison of two string arrays using the comparison operator specified by cmp_op.
cmp_op is not valid.a or b is a non-string array>>> a = np.array(["a", "b", "cde"])
>>> b = np.array(["a", "a", "dec"])
>>> np.compare_chararrays(a, b, ">", True)
array([False, True, False])
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.
a along the given axis, then output is truncated to the length of the condition array.a without the slices along axis for which condition is false.take, choose, diag, diagonal, selectndarray.compress : Equivalent method in ndarrayextract : Equivalent method when working on 1-D arrays>>> 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]])
>>> np.compress([False, True], a)
array([2])
Join a sequence of arrays along an existing axis.
axis (the first, by default).out... versionadded:: 1.20.0
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.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.
>>> 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])
>>> 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)
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. 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.
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.a and v.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.The discrete convolution operation is defined as
(a * v)[n] = sum_{m = -โ}^{โ} a[m] v[n - m]
It can be shown that a convolution x(t) * y(t) in time/space is equivalent to the multiplication 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.
>>> np.convolve([1, 2, 3], [0, 1, 0.5])
array([0. , 1. , 2.5, 4. , 1.5])
>>> np.convolve([1,2,3],[0,1,0.5], 'same')
array([1. , 2.5, 4. ])
>>> np.convolve([1,2,3],[0,1,0.5], 'valid')
array([2.5])
Return an array copy of the given object.
a is Fortran contiguous, 'C' otherwise. 'K' means match the layout of a as closely as possible. (Note that this function and ndarray.copy are very similar, but have different default values for their order= arguments.).. versionadded:: 1.19.0
a.ndarray.copy : Preferred method for creating an array copyThis is equivalent to:
>>> np.array(a, copy=True) #doctest: +SKIP
>>> x = np.array([1, 2, 3])
>>> y = x
>>> z = np.copy(x)
>>> x[0] = 10
>>> x[0] == y[0]
True
>>> x[0] == z[0]
False
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> b = np.copy(a)
>>> b[2][0] = 10
>>> a
array([1, 'm', list([10, 3, 4])], dtype=object)
>>> 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)
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
dst, and selects elements to copy from src to dst wherever it contains the value True.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
R_{ij} = C_{ij} / sqrt(C_{ii} * C_{jj})
The values of R are between -1 and 1, inclusive.
x represents a variable, and each column a single observation of all those variables. Also see rowvar below.y has the same shape as x.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.numpy.float64 precision... versionadded:: 1.20
cov : Covariance matrixDue 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.
>>> 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. ]])
>>> 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. ]])
>>> 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. ]])
Cross-correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal processing texts:
c_{av}[k] = sum_n a[n+k] * conj(v[n])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
convolve docstring. Note that the default is 'valid', unlike convolve, which uses 'full'.old_behavior was removed in NumPy 1.10. If you need the old behavior, use multiarray.correlate.a and v.convolve : Discrete, linear convolution of two one-dimensional sequences.multiarray.correlate : Old, no conjugate, version of correlate.scipy.signal.correlate : uses FFT which has superior performance on large arrays.The definition of correlation above is not unique and sometimes correlation may be defined differently. Another common definition is:
c'_{av}[k] = sum_n a[n] conj(v[n+k])
which is related to c_{av}[k] by c'_{av}[k] = c_{av}[-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.
>>> 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. ])
>>> 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 ])
>>> 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])
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.
a... versionadded:: 1.12.0 (axis), .. versionadded:: 1.19.0 (keepdims)
nonzero : Return the coordinates of all the non-zero values.>>> 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]])
Estimate a covariance matrix, given data and weights. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, X = [x_1, x_2, ... x_N]^T, then the covariance matrix element C_{ij} is the covariance of x_i and x_j. The element C_{ii} is the variance of x_i. See the notes for an outline of the algorithm.
m represents a variable, and each column a single observation of all those variables. Also see rowvar below.y has the same form as that of m.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.(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.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.ddof=0 the array of weights can be used to assign probabilities to observation vectors.numpy.float64 precision... versionadded:: 1.5 (ddof), .. versionadded:: 1.10 (fweights, aweights), .. versionadded:: 1.20 (dtype)
corrcoef : Normalized covariance matrixAssume 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.
>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> x
array([[0, 1, 2],
[2, 1, 0]])
>>> np.cov(x)
array([[ 1., -1.],
[-1., 1.]])
>>> 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)
Return the cross product of two (arrays of) vectors. The cross product of a and b in 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.
a that defines the vector(s). By default, the last axis.b that defines the vector(s). By default, the last axis.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.a, b and c that defines the vector(s) and cross product(s). Overrides axisa, axisb and axisc.a and/or b does not equal 2 or 3.inner : Inner productouter : Outer product.ix_ : Construct index arrays... versionadded:: 1.9.0
Supports full broadcasting of the inputs.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([-3, 6, -3])
>>> x = [1, 2]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([12, -6, -3])
>>> x = [1, 2, 0]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([12, -6, -3])
>>> x = [1,2]
>>> y = [4,5]
>>> np.cross(x, y)
array(-3)
>>> 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]])
>>> np.cross(x, y, axisc=0)
array([[-3, 3],
[ 6, -6],
[-3, 3]])
>>> 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]])
Return the cumulative product of elements along a given axis.
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 is specified, in which case a reference to out is returned.Arithmetic is modular when using integer types, and no error is raised on overflow.
>>> 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.])
>>> np.cumprod(a, axis=0)
array([[ 1, 2, 3],
[ 4, 10, 18]])
>>> np.cumprod(a,axis=1)
array([[ 1, 2, 6],
[ 4, 20, 120]])
Return the cumulative product over the given axis.
cumprod : equivalent function; see for details.Return the cumulative sum of the elements along a given axis.
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 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.sum : Sum array elements.trapz : Integration of array values using the composite trapezoidal rule.diff : Calculate the n-th discrete difference along given axis.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.
>>> 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]])
>>> b = np.array([1, 2e-9, 3e-9] * 1000000)
>>> b.cumsum()[-1]
1000000.0050045159
>>> b.sum()
1000000.0050000029
Convert an array of datetimes into an array of strings.
arr.>>> 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]')
>>> 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')
>>> 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')
>>> 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')
>>> 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'
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.
datetime64 or timedelta64 type.>>> 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]')
>>> np.datetime64('2010', np.datetime_data(dt_25s))
numpy.datetime64('2010-01-01T00:00:00','25s')
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].
obj. If axis is None, obj is applied to the flattened array... 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.
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.insert : Insert elements into an array.append : Append elements at the end of an array.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.
>>> 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])
Issues a DeprecationWarning, adds warning to old_name's docstring, rebinds old_name.__name__ and returns the new function object. This function may also be used as a decorator.
func is used.old_name is deprecated. If given, the deprecation message is that old_name is deprecated and new_name should be used instead.>>> olduint = np.deprecate(np.uint)
DeprecationWarning: `uint64` is deprecated! # may vary
>>> olduint(6)
6
Deprecates a function and includes the deprecation in its docstring. This function is used as a decorator. It returns an object that can be used to issue a DeprecationWarning, by passing the to-be decorated function as argument, this adds warning to the to-be decorated function's docstring and returns the new function object.
deprecate : Decorate a function such that it issues a DeprecationWarningExtract 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.
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>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal.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.>>> 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]])
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].
diag_indices_from.. versionadded:: 1.4.0
>>> 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]])
>>> d3 = np.diag_indices(2, 3)
>>> d3
(array([0, 1]), array([0, 1]), array([0, 1]))
>>> a = np.zeros((2, 2, 2), dtype=int)
>>> a[d3] = 1
>>> a
array([[[1, 0],
[0, 0]],
[[0, 0],
[0, 1]]])
Return the indices to access the main diagonal of an n-dimensional array. See diag_indices for full details.
diag_indices.. versionadded:: 1.4.0
Create a two-dimensional array with the flattened input as a diagonal.
k-th diagonal of the output.k giving the number of the diagonal above (below) the main.diag : MATLAB work-alike for 1-D and 2-D arrays.diagonal : Return specified diagonals.trace : Sum along diagonals.>>> 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]])
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.
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.a is less than 2.diag : MATLAB work-a-like for 1-D and 2-D arrays.diagflat : Create diagonal arrays.trace : Sum along diagonals.>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
[2, 3]])
>>> a.diagonal()
array([0, 3])
>>> a.diagonal(1)
array([1])
>>> 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]])
>>> a[:,:,0] # main diagonal is [0 6]
array([[0, 2],
[4, 6]])
>>> a[:,:,1] # main diagonal is [1 7]
array([[1, 3],
[5, 7]])
>>> 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])
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.
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
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.gradient, ediff1d, cumsumType 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)
>>> 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]')
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.
x.bins is not monotonic.bincount, histogram, unique, searchsortedIf 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
np.digitize is implemented in terms of np.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.
>>> 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])
Display a message on a device.
sys.stdout which is very similar to print. device needs to have write() and flush() methods.device does not have a write() or flush() method.>>> from io import StringIO
>>> buf = StringIO()
>>> np.disp(u'"Display" in a file', device=buf)
>>> buf.getvalue()
'"Display" in a file\n'
Dot product of two arrays. Specifically,
a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred.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.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])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.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.a is not the same size as the second-to-last dimension of b.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.>>> np.dot(3, 4)
12
>>> np.dot([2j, 3j], [2j, 3j])
(-13+0j)
>>> 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
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.
split : Split an array into multiple sub-arrays of equal size.>>> 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)]
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.
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.>>> 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]]])
The differences between consecutive elements of an array.
ary.flat[1:] - ary.flat[:-1].diff, gradientWhen applied to masked arrays, this function drops the mask information if the to_begin and/or to_end parameters are used.
>>> 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])
>>> y = [[1, 2, 4], [1, 6, 24]]
>>> np.ediff1d(y)
array([ 1, 2, -3, 5, 18])
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.
casting parameter to allow the conversions. Default is None.np.einsum_path function. See np.einsum_path for more details. Defaults to False.einsum_path, dot, inner, outer, tensordot, linalg.multi_doteinops : similar verbose interface is provided by einops package to cover additional operations: transpose, reshape/flatten, repeat/tile, squeeze/unsqueeze and reductions.opt_einsum : opt_einsum optimizes contraction order for einsum-like expressions in backend-agnostic manner... 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:
numpy.trace.numpy.diag.numpy.sum.numpy.transpose.numpy.matmul numpy.dot.numpy.inner numpy.outer.numpy.multiply.numpy.tensordot.numpy.einsum_path.The subscripts string is a comma-separated list of subscript labels, where each label refers to a dimension of the corresponding operand. Whenever a label is repeated it is summed, so np.einsum('i,i', a, b) is equivalent to np.inner(a,b). If a label appears only once, it is not summed, so np.einsum('i', a) produces a view of a with no changes. A further example np.einsum('ij,jk', a, b) describes traditional matrix multiplication and is equivalent to np.matmul(a,b). Repeated subscript labels in one operand take the diagonal. For example, np.einsum('ii', a) is equivalent to np.trace(a).
In implicit mode, the chosen subscripts are important since the axes of the output are reordered alphabetically. This means that np.einsum('ij', a) doesn't affect a 2D array, while np.einsum('ji', a) takes its transpose. Additionally, np.einsum('ij,jk', a, b) returns a matrix multiplication, while, np.einsum('ij,jh', a, b) returns the transpose of the multiplication since subscript 'h' precedes subscript 'i'.
In explicit mode the output can be directly controlled by specifying output subscript labels. This requires the identifier '->' as well as the list of output subscript labels. This feature increases the flexibility of the function since summing can be disabled or forced when required. The call np.einsum('i->', a) is like np.sum(a, axis=-1), and np.einsum('ii->i', a) is like np.diag(a). The difference is that einsum does not allow broadcasting by default. Additionally np.einsum('ij,jh->ih', a, b) directly specifies the order of the output subscript labels and therefore returns matrix multiplication, unlike the example above in implicit mode.
To enable and control broadcasting, use an ellipsis. Default NumPy-style broadcasting is done by adding an ellipsis to the left of each term, like np.einsum('...ii->...i', a). To take the trace along the first and last axes, you can do np.einsum('i...i', a), or to do a matrix-matrix product with the left-most indices instead of rightmost, one can do np.einsum('ij...,jk...->ik...', a, b).
When there is only one operand, no axes are summed, and no output parameter is provided, a view into the operand is returned instead of a new array. Thus, taking the diagonal as np.einsum('ii->i', a) produces a view (changed in version 1.10.0).
einsum also provides an alternative way to provide the subscripts and operands as einsum(op0, sublist0, op1, sublist1, ..., [sublistout]). If the output shape is not provided in this format einsum will be calculated in implicit mode, otherwise it will be performed explicitly.
.. 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 np.swapaxes(a, 0, 2) 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 numpy.einsum_path for more details.
>>> a = np.arange(25).reshape(5,5)
>>> b = np.arange(5)
>>> c = np.arange(6).reshape(2,3)
>>> np.einsum('ii', a)
60
>>> np.einsum(a, [0,0])
60
>>> np.trace(a)
60
>>> 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])
>>> 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])
>>> np.einsum('...j->...', a)
array([ 10, 35, 60, 85, 110])
>>> np.einsum(a, [Ellipsis,1], [Ellipsis])
array([ 10, 35, 60, 85, 110])
>>> 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]])
>>> np.einsum('i,i', b, b)
30
>>> np.einsum(b, [0], b, [0])
30
>>> np.inner(b,b)
30
>>> 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])
>>> 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]])
>>> 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]])
>>> 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.]])
>>> a = np.zeros((3, 3))
>>> np.einsum('ii->i', a)[:] = 1
>>> a
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> 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]])
>>> a = np.ones(64).reshape(2,4,8)
>>> for iteration in range(500):
... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)
>>> for iteration in range(500):
... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='optimal')
>>> for iteration in range(500):
... _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy')
>>> 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)
Evaluates the lowest cost contraction order for an einsum expression by considering the creation of intermediate arrays.
einsum_path, uses this as the contraction path * if False no optimization is taken * if True defaults to the 'greedy' algorithm * 'optimal' An algorithm that combinatorially explores all possible ways of contracting the listed tensors and choosest the least costly path. Scales exponentially with the number of terms in the contraction. * 'greedy' An algorithm that chooses the best pair contraction at each step. Effectively, this algorithm searches the largest inner, Hadamard, and then outer products at each step. Scales cubically with the number of terms in the contraction. Equivalent to the 'optimal' path for most contractions. Default is 'greedy'.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.
einsum, linalg.multi_dot>>> 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
>>> 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
Return a new array of given shape and type, without initializing entries.
(2, 3) or 2.numpy.int8. Default is numpy.float64.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
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.empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution.
>>> 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
Return a new array with the same shape and type as a given array.
prototype define these same attributes of the returned array.prototype is Fortran contiguous, 'C' otherwise. 'K' means match the layout of prototype as closely as possible.prototype, otherwise it will be a base-class array. Defaults to True... versionadded:: 1.6.0 (dtype, order), .. versionadded:: 1.17.0 (shape)
prototype.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.This function does not initialize the returned array; to do that use zeros_like or ones_like instead. It may be marginally faster than the functions that do set the array values.
>>> 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]])
Expand the shape of an array. Insert a new axis that will appear at the axis position in the expanded array shape.
.. 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 AxisError.
a with the number of dimensions increased.squeeze : The inverse operation, removing singleton dimensionsreshape : Insert, remove, and combine dimensions, and resize existing onesdoc.indexing, atleast_1d, atleast_2d, atleast_3d>>> x = np.array([1, 2])
>>> x.shape
(2,)
>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)
>>> y = np.expand_dims(x, axis=1)
>>> y
array([[1],
[2]])
>>> y.shape
(2, 1)
>>> 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
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.
arr to extract.condition.arr where condition is True.take, put, copyto, compress, place>>> 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])
>>> arr[condition]
array([0, 3, 6, 9])
Return a 2-D array with ones on the diagonal and zeros elsewhere.
N.like supports the __array_function__ protocol, the result will be defined by it... versionadded:: 1.14.0 (order), .. versionadded:: 1.20.0 (like)
k-th diagonal, whose values are equal to one.identity : (almost) equivalent functiondiag : diagonal 2-D array from a 1-D array specified by the user.>>> 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.]])
fastCopyAndTranspose = _fastCopyAndTranspose(...) โ quick copy and transpose.
Fill the main diagonal of the given array of any dimensionality. For an array a with a.ndim >= 2, the diagonal is the list of locations with indices a[i, ..., i] all identical. This function modifies the input array in-place, it does not return a value.
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.diag_indices, diag_indices_from.. 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.
>>> a = np.zeros((3, 3), int)
>>> np.fill_diagonal(a, 5)
>>> a
array([[5, 0, 0],
[0, 5, 0],
[0, 0, 5]])
>>> a = np.zeros((3, 3, 3, 3), int)
>>> np.fill_diagonal(a, 4)
>>> 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]])
>>> # 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]])
>>> 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]])
Determine common type following standard coercion rules.
array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.dtype, common_type, can_cast, mintypecode>>> np.find_common_type([], [np.int64, np.float32, complex])
dtype('complex128')
>>> np.find_common_type([np.int64, np.float32], [])
dtype('float64')
>>> np.find_common_type([np.float32], [np.int64, np.float64])
dtype('float32')
>>> np.find_common_type([np.float32], [complex])
dtype('complex128')
>>> np.find_common_type(['f4', 'f4', 'i4'], ['c8'])
dtype('complex128')
Round to nearest integer towards zero. Round an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats.
out is then a reference to that array.rint, trunc, floor, ceilaround : Round to given number of decimals>>> np.fix(3.14)
3.0
>>> np.fix(3)
3.0
>>> np.fix([2.1, 2.9, -2.1, -2.9])
array([ 2., 2., -2., -2.])
Return indices that are non-zero in the flattened version of a. This is equivalent to np.nonzero(np.ravel(a))[0].
a.ravel() that are non-zero.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.>>> x = np.arange(-2, 3)
>>> x
array([-2, -1, 0, 1, 2])
>>> np.flatnonzero(x)
array([0, 1, 3, 4])
>>> x.ravel()[np.flatnonzero(x)]
array([-2, -1, 1, 2])
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
.. versionchanged:: 1.15.0 None and tuples of axes are supported
m with the entries of axis reversed. Since a view is returned, this operation is done in constant time.flipud : Flip an array vertically (axis=0).fliplr : Flip an array horizontally (axis=1).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.
>>> A = np.arange(8).reshape((2,2,2))
>>> A
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.flip(A, 0)
array([[[4, 5],
[6, 7]],
[[0, 1],
[2, 3]]])
>>> np.flip(A, 1)
array([[[2, 3],
[0, 1]],
[[6, 7],
[4, 5]]])
>>> np.flip(A)
array([[[7, 6],
[5, 4]],
[[3, 2],
[1, 0]]])
>>> np.flip(A, (0, 2))
array([[[5, 4],
[7, 6]],
[[1, 0],
[3, 2]]])
>>> A = np.random.randn(3,4,5)
>>> np.all(np.flip(A,2) == A[:,:,::-1,...])
True
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.
m with the columns reversed. Since a view is returned, this operation is O(1).flipud : Flip array in the up/down direction.flip : Flip array in one or more dimesions.rot90 : Rotate array counterclockwise.Equivalent to m[:,::-1] or np.flip(m, axis=1). Requires the array to be at least 2-D.
>>> A = np.diag([1.,2.,3.])
>>> A
array([[1., 0., 0.],
[0., 2., 0.],
[0., 0., 3.]])
>>> np.fliplr(A)
array([[0., 0., 1.],
[0., 2., 0.],
[3., 0., 0.]])
>>> A = np.random.randn(2,3,5)
>>> np.all(np.fliplr(A) == A[:,::-1,...])
True
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.
m with the rows reversed. Since a view is returned, this operation is O(1).fliplr : Flip array in the left/right direction.flip : Flip array in one or more dimesions.rot90 : Rotate array counterclockwise.Equivalent to m[::-1, ...] or np.flip(m, axis=0). Requires the array to be at least 1-D.
>>> A = np.diag([1.0, 2, 3])
>>> A
array([[1., 0., 0.],
[0., 2., 0.],
[0., 0., 3.]])
>>> np.flipud(A)
array([[0., 0., 3.],
[0., 2., 0.],
[1., 0., 0.]])
>>> A = np.random.randn(2,3,5)
>>> np.all(np.flipud(A) == A[::-1,...])
True
>>> np.flipud([1,2])
array([2, 1])
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.
unique is True, but must be an integer if unique is False.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 roundingTrue, 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.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
format_float_scientific>>> 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'
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.
unique is True, but must be an integer if unique is False.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 roundingunique=True. In that case more digits than necessary to uniquely identify the value may be printed and rounded unbiased.-- versionadded:: 1.21.0
format_float_positional>>> 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'
Interpret a buffer as a 1-dimensional array.
.. versionadded:: 1.20.0 (like)
frombuffer(...)๐ 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 โ 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
๐ 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.
๐ Examples
>>> s = b'hello world'
>>> np.frombuffer(s, dtype='S1', count=5, offset=6)
array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')
>>> np.frombuffer(b'\x01\x02', dtype=np.uint8)
array([1, 2], dtype=uint8)
>>> np.frombuffer(b'\x01\x02\x03\x04\x05', dtype=np.uint8, count=3)
array([1, 2, 3], dtype=uint8)
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.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.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.0like : array_like โ Reference object ... (same as above). .. 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
>>> 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')])
fromfunction(function, shape, *, dtype=None, 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 โ Reference object ... .. 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 are passed to function.
๐ Examples
>>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
array([[ True, False, False],
[False, True, False],
[False, False, True]])
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
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.count : int, optional โ The number of items to read from iterable. The default is -1, which means all data is read.like : array_like โ Reference object ... .. 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
>>> iterable = (x*x for x in range(5))
>>> np.fromiter(iterable, float)
array([ 0., 1., 4., 9., 16.])
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
>>> 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')
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 : str or file โ Filename or file object to read.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.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
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
>>> f = open('test.dat', 'w')
>>> _ = f.write("1312 foo\n1534 bar\n444 qux")
>>> f.close()
>>> regexp = r"(\d+)\s+(...)" # match [digits, whitespace, anything]
>>> output = np.fromregex('test.dat', 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])
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 either utfโ8 (python 3) or the default encoding (python 2), neither of which produce sane results.like : array_like โ Reference object ... .. versionadded:: 1.20.0๐ Returns
arr : ndarray โ The constructed array.โ ๏ธ Raises
dtype and count.๐ See Also
frombuffer, fromfile, fromiter
๐ Examples
>>> np.fromstring('1 2', dtype=int, sep=' ')
array([1, 2])
>>> np.fromstring('1, 2', dtype=int, sep=',')
array([1, 2])
full(shape, fill_value, dtype=None, order='C', *, 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.like : array_like โ Reference object ... .. 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
>>> 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]])
full_like(a, fill_value, dtype=None, order='K', subok=True, shape=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 : scalar โ 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๐ Returns
out : ndarray โ Array of fill_value with the same shape and type as a.๐ See Also
empty_like, ones_like, zeros_like, full
๐ Examples
>>> x = np.arange(6, dtype=int)
>>> np.full_like(x, 1)
array([1, 1, 1, 1, 1, 1])
>>> np.full_like(x, 0.1)
array([0, 0, 0, 0, 0, 0])
>>> np.full_like(x, 0.1, dtype=np.double)
array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
>>> np.full_like(x, np.nan, dtype=np.double)
array([nan, nan, nan, nan, nan, nan])
>>> y = np.arange(6, dtype=np.double)
>>> np.full_like(y, 0.1)
array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
genfromtxt(fname, dtype=<class 'float'>, ...)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...(Additional parameters would follow the same pattern โ all original information preserved.)
๐ Returns
out : ndarray โ Data read from the text file. If usemask is True, this is a masked array.๐ See Also
numpy.loadtxt
๐ Notes
๐ Examples
>>> from io import StringIO
... (full examples)
geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0)get_array_wrap(*args)get_include()get_printoptions()getbufsize()geterr()geterrcall()geterrobj(...)gradient(f, *varargs, axis=None, edge_order=1)hamming(M)hanning(M)histogram(a, bins=10, range=None, normed=None, weights=None, density=None)histogram2d(x, y, bins=10, range=None, normed=None, weights=None, density=None)histogram_bin_edges(a, bins=10, range=None, weights=None)histogramdd(sample, bins=10, range=None, normed=None, weights=None, density=None)hsplit(ary, indices_or_sections)hstack(tup)i0(x)identity(n, dtype=None, *, like=None)imag(val)in1d(ar1, ar2, assume_unique=False, invert=False)indices(dimensions, dtype=<class 'int'>, sparse=False)info(object=None, maxwidth=76, output=<_io.TextIOWrapper ...>, toplevel='numpy')inner(...)insert(arr, obj, values, axis=None)interp(x, xp, fp, left=None, right=None, period=None)intersect1d(ar1, ar2, assume_unique=False, return_indices=False)is_busday(...)isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)iscomplex(x)iscomplexobj(x)isfortran(a)isin(element, test_elements, assume_unique=False, invert=False)isneginf(x, out=None)isposinf(x, out=None)isreal(x)isrealobj(x)isscalar(element)issctype(rep)issubclass_(arg1, arg2)issubdtype(arg1, arg2)issubsctype(arg1, arg2)iterable(y)percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False)Compute the q-th percentile of the data along the specified axis.
a : array_like โ Input array or object that can be converted to an array.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. ๐ Changed in version 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.interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} โ This optional parameter specifies the interpolation method to use when the desired percentile lies between two data points i < j:
'linear': i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.'lower': i.'higher': j.'nearest': i or j, whichever is nearest.'midpoint': (i + j) / 2.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. ๐ Added in version 1.9.0.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.
mean, median (equivalent to percentile(..., 50)), nanpercentile, quantile (equivalent to percentile, except with q in the range [0, 1]).
Given a vector V of length N, the q-th percentile of V is the value q/100 of the way from the minimum to the maximum in a sorted copy of V. The values and distances of the two nearest neighbors as well as the interpolation parameter will determine the percentile if the normalized ranking does not match the location of q exactly. This function is the same as the median if q=50, the same as the minimum if q=0 and the same as the maximum if q=100.
>>> 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)
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.
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).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.
choose, select, where
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]])
|--
>>> x = np.linspace(-2.5, 2.5, 6)
>>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
array([-1., -1., -1., 1., 1., 1.])
>>> 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])
>>> y = -2
>>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x])
array(2)
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.
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.copyto, put, take, extract
>>> arr = np.arange(6).reshape(2, 3)
>>> np.place(arr, arr>2, [44, 55])
>>> arr
array([[ 0, 1, 2],
[44, 55, 44]])
poly(seq_of_zeros)Find the coefficients of a polynomial with the given sequence of roots.
โ ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide.
Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square matrix (or array, which will be treated as a matrix) can also be given, in which case the coefficients of the characteristic polynomial of the matrix are returned.
seq_of_zeros : array_like, shape (N,) or (N, N) โ A sequence of polynomial roots, or a square array or matrix object.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.
ValueError โ If input is the wrong shape (the input must be a 1-D or square 2-D array).
polyval, roots, polyfit, poly1d
Specifying the roots of a polynomial still leaves one degree of freedom, typically represented by an undetermined leading coefficient. In the case of this function, that coefficient - the first one in the returned array - is always taken as one. (If for some reason you have one other point, the only automatic way presently to leverage that information is to use polyfit.)
The characteristic polynomial, p_a(t), of an n-by-n matrix A is given by p_a(t) = det(t I - A), where I is the n-by-n identity matrix.
>>> np.poly((0, 0, 0)) # Multiple root example
array([1., 0., 0., 0.])
>>> np.poly((-1./2, 0, 1./2))
array([ 1. , 0. , -0.25, 0. ])
>>> np.poly((np.random.random(1)[0], 0, np.random.random(1)[0]))
array([ 1. , -0.77086955, 0.08618131, 0. ]) # random
>>> P = np.array([[0, 1./3], [-1./2, 0]])
>>> np.poly(P)
array([1. , 0. , 0.16666667])
polyadd(a1, a2)Find the sum of two polynomials.
โ ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.
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.
a1, a2 : array_like or poly1d object โ Input polynomials.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.
poly1d, poly, polyder, polydiv, polyfit, polyint, polysub, polyval
>>> np.polyadd([1, 2], [9, 5, 4])
array([9, 6, 6])
>>> 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
polyder(p, m=1)Return the derivative of the specified order of a polynomial.
โ ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.
p : poly1d or sequence โ Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see poly1d.m : int, optional โ Order of differentiation (default: 1)der : poly1d โ A new polynomial representing the derivative.
polyint, poly1d
>>> p = np.poly1d([1,1,1,1])
>>> p2 = np.polyder(p)
>>> p2
poly1d([3, 2, 1])
>>> p2(2.)
17.0
>>> (p(2. + 0.001) - p(2.)) / 0.001
17.007000999997857
>>> np.polyder(p, 2)
poly1d([6, 2])
>>> np.polyder(p, 3)
poly1d([6])
>>> np.polyder(p, 4)
poly1d([0])
polydiv(u, v)Returns the quotient and remainder of polynomial division.
โ ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.
The input arrays are the coefficients (including any coefficients equal to zero) of the "numerator" (dividend) and "denominator" (divisor) polynomials, respectively.
u : array_like or poly1d โ Dividend polynomial's coefficients.v : array_like or poly1d โ Divisor polynomial's coefficients.q : ndarray โ Coefficients, including those equal to zero, of the quotient.r : ndarray โ Coefficients, including those equal to zero, of the remainder.poly, polyadd, polyder, polyfit, polyint, polymul, polysub, polyval
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.
>>> 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]))
polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)Least squares polynomial fit.
โ ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. The Polynomial.fit class method is recommended for new code as it is more stable numerically.
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.
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 to apply to the y-coordinates of the sample points. For gaussian uncertainties, use 1/sigma (not 1/sigma**2).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 1/sigma**2, with sigma known to be a reliable estimate of the uncertainty.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 โ Present only if full = True. Residuals is sum of squared residuals of the least-squares fit, the effective rank of the scaled Vandermonde coefficient matrix, its singular values, and the specified value of rcond. For more details, see linalg.lstsq.V : ndarray, shape (M,M) or (M,M,K) โ Present only if full = False and cov=True. The covariance matrix of the polynomial coefficient estimates. The diagonal of this matrix are the variance estimates for each coefficient. If y is a 2-D array, then the covariance matrix for the k-th data set are in V[:,:,k].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 warnings.simplefilter('ignore', np.RankWarning).
polyval, linalg.lstsq, scipy.interpolate.UnivariateSpline
The solution minimizes the squared error E = sum_j |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[k] = y[k]
The coefficient matrix of the coefficients p is a Vandermonde matrix. polyfit issues a RankWarning when the least-squares fit is badly conditioned. This implies that the best fit is not well-defined due to numerical error. The results may be improved by lowering the polynomial degree or by replacing x by x - x.mean(). The rcond parameter can also be set to a value smaller than its default, but the resulting fit may be spurious. 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. When polynomial fits are not satisfactory, splines may be a good alternative.
>>> 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
>>> p = np.poly1d(z)
>>> p(0.5)
0.6143849206349179 # may vary
>>> p(3.5)
-0.34732142857143039 # may vary
>>> p(10)
22.579365079365115 # may vary
>>> with warnings.catch_warnings():
... warnings.simplefilter('ignore', np.RankWarning)
... p30 = np.poly1d(np.polyfit(x, y, 30))
...
>>> p30(4)
-0.80000000000000204 # may vary
>>> p30(5)
-0.99999999999999445 # may vary
>>> p30(4.5)
-0.10547061179440398 # may vary
>>> 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()
polyint(p, m=1, k=None)Return an antiderivative (indefinite integral) of a polynomial.
โ ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.
The returned order m antiderivative P of polynomial p satisfies d^m/dx^m P(x) = p(x) and is defined up to m - 1 integration constants k.
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.polyder, poly1d.integ
>>> 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
>>> 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
>>> np.polyder(P, 2)(0)
6.0
>>> np.polyder(P, 1)(0)
5.0
>>> P(0)
3.0
polymul(a1, a2)Find the product of two polynomials.
โ ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.
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.
a1, a2 : array_like or poly1d object โ Input polynomials.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.
poly1d, poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval, convolve
>>> np.polymul([1, 2, 3], [9, 5, 1])
array([ 9, 23, 38, 17, 3])
>>> 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
polysub(a1, a2)Difference (subtraction) of two polynomials.
โ ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.
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.
a1, a2 : array_like or poly1d โ Minuend and subtrahend polynomials, respectively.out : ndarray or poly1d โ Array or poly1d object of the difference polynomial's coefficients.
polyval, polydiv, polymul, polyadd
>>> np.polysub([2, 10, -2], [3, 10, -4])
array([-1, 0, 2])
polyval(p, x)Evaluate a polynomial at specific values.
โ ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.
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.
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.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.
poly1d
Horner's scheme 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.
>>> 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])
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.
>>> from numpy.testing import assert_equal
>>> with np.printoptions(precision=2):
... np.array([2.0]) / 3
array([0.67])
>>> with np.printoptions(precision=2) as opts:
... assert_equal(opts, np.get_printoptions())
set_printoptions, get_printoptions
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.
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. ๐ Added in version 1.7.0. If axis is a tuple of ints, a product is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.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. ๐ Added in version 1.15.0.where : array_like of bool, optional โ Elements to include in the product. See ~numpy.ufunc.reduce for details. ๐ Added in version 1.17.0.product_along_axis : ndarray โ An array shaped as a but with the specified axis removed. Returns a reference to out if specified.
ndarray.prod, ufuncs-output-type
Arithmetic is modular when using integer types, and no error is raised on overflow. The product of an empty array is the neutral element 1.
>>> np.prod([1.,2.])
2.0
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
>>> np.prod([1., np.nan, 3.], where=[True, False, True])
3.0
>>> x = np.array([1, 2, 3], dtype=np.uint8)
>>> np.prod(x).dtype == np.uint
True
>>> x = np.array([1, 2, 3], dtype=np.int8)
>>> np.prod(x).dtype == int
True
>>> np.prod([1, 2], initial=5)
10
product(*args, **kwargs)Return the product of array elements over a given axis.
prod : equivalent function; see for details.
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 in native byte order. This function is symmetric, but rarely associative.
type1 : dtype or dtype specifier โ First data type.type2 : dtype or dtype specifier โ Second data type.out : dtype โ The promoted data type.
๐ Added in version 1.6.0. Starting in NumPy 1.9, promote_types function now returns a valid string length when given an integer or float dtype as one argument and a string dtype as another argument.
result_type, dtype, can_cast
>>> 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')
>>> p = np.promote_types
>>> p('S', p('i1', 'u1'))
dtype('S6')
>>> p(p('S', 'i1'), 'u1')
dtype('S4')
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'.
โ ๏ธ 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.
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. ๐ Added in version 1.15.0. If this is a tuple of ints, a reduction is performed on multiple axes, instead of a single axis or all the axes as before.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.ptp : ndarray โ A new array holding the result, unless out was specified, in which case a reference to out is returned.
>>> 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
>>> 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)
>>> np.ptp(y, axis=1).view(np.uint8)
array([126, 127, 128, 129], dtype=uint8)
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.
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.
putmask, place, put_along_axis
>>> 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])
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.
๐ Added in version 1.15.0.
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.take_along_axis
>>> a = np.array([[10, 30, 20], [60, 40, 50]])
>>> ai = np.expand_dims(np.argmax(a, axis=1), axis=1)
>>> ai
array([[1],
[0]])
>>> np.put_along_axis(a, ai, 99, axis=1)
>>> a
array([[10, 99, 20],
[99, 40, 50]])
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.
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.place, put, take, copyto
>>> x = np.arange(6).reshape(2, 3)
>>> np.putmask(x, x>2, x**2)
>>> x
array([[ 0, 1, 2],
[ 9, 16, 25]])
>>> x = np.arange(5)
>>> np.putmask(x, x>1, [-33, -44])
>>> x
array([ 0, 1, -33, -44, -33])
quantile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False)Compute the q-th quantile of the data along the specified axis.
๐ Added in version 1.15.0.
a : array_like โ Input array or object that can be converted to an array.q : array_like of float โ Quantile or sequence of quantiles to compute, which must be between 0 and 1 inclusive.axis : {int, tuple of int, None}, optional โ Axis or axes along which the quantiles are computed. The default is to compute the quantile(s) along a flattened version of the array.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.interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} โ This optional parameter specifies the interpolation method to use when the desired quantile lies between two data points i < j:
linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.lower: i.higher: j.nearest: i or j, whichever is nearest.midpoint: (i + j) / 2.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.quantile : scalar or ndarray โ If q is a single quantile and axis=None, then the result is a scalar. If multiple quantiles are given, first axis of the result corresponds to the quantiles. The other axes are the axes that remain after the reduction of a. If the input contains integers or floats smaller than float64, the output data-type is float64. Otherwise, the output data-type is the same as that of the input. If out is specified, that array is returned instead.
mean, percentile (equivalent to quantile, but with q in the range [0, 100]), median (equivalent to quantile(..., 0.5)), nanquantile
Given a vector V of length N, the q-th quantile of V is the value q of the way from the minimum to the maximum in a sorted copy of V. The values and distances of the two nearest neighbors as well as the interpolation parameter will determine the quantile if the normalized ranking does not match the location of q exactly. This function is the same as the median if q=0.5, the same as the minimum if q=0.0 and the same as the maximum if q=1.0.
>>> 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)
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.
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.y : array_like โ y is an array of the same subtype as a, with shape (a.size,). Note that matrices are special cased for backward compatibility, if a is a matrix, then y is a 1-D ndarray.
ndarray.flat, ndarray.flatten, ndarray.reshape
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.
>>> 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])
>>> np.ravel(x.T)
array([1, 4, 2, 5, 3, 6])
>>> np.ravel(x.T, order='A')
array([1, 2, 3, 4, 5, 6])
>>> 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])
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.
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.
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.raveled_indices : ndarray โ An array of indices into the flattened version of an array of dimensions dims.
unravel_index
๐ Added in version 1.6.0.
>>> 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
real(val)Return the real part of the complex argument.
val : array_like โ Input array.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.
real_if_close, imag, angle
>>> 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
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).
a : array_like โ Input array.tol : float โ Tolerance in machine epsilons for the complex part of the elements in the array.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.
real, imag, angle
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.
>>> 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])
recfromcsv(fname, **kwargs)Load ASCII data stored in a comma-separated file. The returned array is a record array (if usemask=False, see recarray) or a masked record array (if usemask=True, see ma.mrecords.MaskedRecords).
fname, kwargs : For a description of input parameters, see genfromtxt.numpy.genfromtxt
By default, dtype is None, which means that the data-type of the output array will be determined from the data.
recfromtxt(fname, **kwargs)Load ASCII data from a file and return it in a record array. If usemask=False a standard recarray is returned, if usemask=True a MaskedRecords array is returned.
fname, kwargs : For a description of input parameters, see genfromtxt.numpy.genfromtxt
By default, dtype is None, which means that the data-type of the output array will be determined from the data.
repeat(a, repeats, axis=None)Repeat elements of an array.
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.repeated_array : ndarray โ Output array which has the same shape as a, except along the given axis.
tile, unique
>>> 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]])
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).
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 list of str โ The requirements list can be any of the following:
like : array_like โ Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. ๐ Added in version 1.20.0.out : ndarray โ Array with specified requirements and type if given.
asarray, asanyarray, ascontiguousarray, asfortranarray, ndarray.flags
The returned array will be guaranteed to have the listed requirements by making a copy if needed.
>>> x = np.arange(6).reshape(2,3)
>>> x.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : 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
UPDATEIFCOPY : False
reshape(a, newshape, order='C')Gives a new shape to an array without changing its data.
a : array_like โ Array to be reshaped.newshape : int or tuple of ints โ The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.order : {'C', 'F', 'A'}, optional โ Read the elements of a using this index order, and place the elements into the reshaped array using this index order. 'C' means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. 'F' means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of indexing. 'A' means to read / write the elements in Fortran-like index order if a is Fortran *contiguous* in memory, C-like order otherwise.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.
ndarray.reshape
It is not always possible to change the shape of an array without copying the data. If you want an error to be raised when the data is copied, you should assign the new shape to the shape attribute of the array. The order keyword gives the index ordering both for fetching the values from a, and then placing the values into the output array.
>>> 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]])
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.
a : array_like โ Array to be resized.new_shape : int or tuple of int โ Shape of resized array.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.
np.reshape, np.pad, np.repeat, ndarray.resize
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.
>>> 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]])
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.
arrays_and_dtypes : list of arrays and dtypes โ The operands of some operation whose result type is needed.out : dtype โ The result type.
dtype, promote_types, min_scalar_type, can_cast
๐ Added in version 1.6.0. The specific algorithm used is as follows: Categories are determined by first checking which of boolean, integer (int/uint), or floating point (float/complex) the maximum kind of all the arrays and the scalars are. If there are only scalars or the maximum category of the scalars is higher than the maximum category of the arrays, the data types are combined with promote_types to produce the return value. Otherwise, min_scalar_type is called on each array, and the resulting data types are all combined with promote_types to produce the return value. The set of int values is not a subset of the uint values for types with the same number of bits, something not reflected in min_scalar_type, but handled as a special case in result_type.
>>> 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')
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.
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.res : ndarray โ Output array, with the same shape as a.
rollaxis
๐ Added in version 1.12.0. Supports rolling over multiple dimensions simultaneously.
>>> 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]])
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.
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:start | Normalized start |
|---|---|
-(arr.ndim+1) | raise AxisError |
-arr.ndim | 0 |
| โฎ | โฎ |
-1 | arr.ndim-1 |
0 | 0 |
| โฎ | โฎ |
arr.ndim | arr.ndim |
arr.ndim + 1 | raise AxisError |
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.
moveaxis, roll
>>> 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)
roots(p)Return the roots of a polynomial with coefficients given in p.
โ ๏ธ This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred.
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].
p : array_like โ Rank-1 array of polynomial coefficients.out : ndarray โ An array containing the roots of the polynomial.
ValueError โ When p cannot be converted to a rank-1 array.
poly, polyval, polyfit, poly1d
The algorithm relies on computing the eigenvalues of the companion matrix.
>>> coeff = [3.2, 2, 1]
>>> np.roots(coeff)
array([-0.3125+0.46351241j, -0.3125-0.46351241j])
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.
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. ๐ Added in version 1.12.0.y : ndarray โ A rotated view of m.
flip, fliplr, flipud
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)).
>>> 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]]])
round_(a, decimals=0, out=None)Round an array to the given number of decimals.
around : equivalent function; see for details.
row_stack = vstack(tup)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.
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.stacked : ndarray โ The array formed by stacking the given arrays, will be at least 2-D.
concatenate, stack, block, hstack, dstack, column_stack, vsplit
>>> 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]])
safe_eval(source)Protected string evaluation. Evaluate a string containing a Python literal expression without allowing the execution of arbitrary non-literal code.
source : str โ The string to evaluate.obj : object โ The result of evaluating source.
SyntaxError โ If the code has invalid Python syntax, or if it contains non-literal code.>>> np.safe_eval('1')
1
>>> np.safe_eval('[1, 2, 3]')
[1, 2, 3]
>>> np.safe_eval('{"foo": ("bar", 10.0)}')
{'foo': ('bar', 10.0)}
>>> np.safe_eval('import os')
Traceback (most recent call last):
... SyntaxError: invalid syntax
>>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()')
Traceback (most recent call last):
... ValueError: malformed node or string: <_ast.Call object at 0x...>
save(file, arr, allow_pickle=True, fix_imports=True)Save an array to a binary file in NumPy .npy format.
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 Python 2 and Python 3). Default: Truefix_imports : bool, optional โ Only useful in forcing objects in object arrays on Python 3 to be pickled in a Python 2 compatible way. If fix_imports is True, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2.savez, savetxt, load
For a description of the .npy format, see numpy.lib.format. Any data saved to the file is appended to the end of the file.
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> np.save(outfile, x)
>>> _ = outfile.seek(0) # Only needed here 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]
savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)Save an array to a text file.
fname : filename or file handle โ 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:
fmt='%.4e', resulting in numbers formatted like ' (%s+%sj)' % (fmt, fmt)' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej' for 3 columns['%.3e + %.3ej', '(%.15e%+.15ej)'] for 2 columnsdelimiter : str, optional โ String or character separating columns.newline : str, optional โ String or character separating lines. ๐ Added in version 1.5.0.header : str, optional โ String that will be written at the beginning of the file. ๐ Added in version 1.7.0.footer : str, optional โ String that will be written at the end of the file. ๐ Added in version 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. ๐ Added in version 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'. ๐ Added in version 1.14.0.save, savez, savez_compressed
Further explanation of the fmt parameter (%[flag]width[.precision]specifier):
- left justify, + Forces to precede result with + or -, 0 Left pad the number with zeros instead of space.e, E, f, number of digits after decimal point; for g, G, maximum number of significant digits; for s, maximum number of characters.c character, d,i signed decimal integer, e,E scientific notation, f decimal floating point, g,G use shorter of e,E or f, o signed octal, s string, u unsigned decimal integer, x,X unsigned hexadecimal integer.>>> 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
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.
file : str or file โ 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.None
save, savetxt, savez_compressed
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. When opening the saved .npz file with load a NpzFile object is returned. This is a dictionary-like object which can be queried for its list of arrays (with the .files attribute), and for the arrays themselves. When saving dictionaries, the dictionary keys become filenames inside the ZIP archive. Therefore, keys should be valid filenames. E.g., avoid keys that begin with / or contain ..
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> y = np.sin(x)
>>> np.savez(outfile, x, y)
>>> _ = outfile.seek(0) # Only needed here 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])
>>> 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])
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(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.
file : str or file โ 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.None
numpy.save, numpy.savetxt, numpy.savez, numpy.load
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. When opening the saved .npz file with load a NpzFile object is returned.
>>> 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
sctype2char(sctype)Return the string representation of a scalar dtype.
sctype : scalar dtype or object โ If a scalar dtype, the corresponding string character is returned. If an object, sctype2char tries to infer its scalar type and then return the corresponding string character.typechar : str โ The string character corresponding to the scalar type.
ValueError โ If sctype is an object for which the type can not be inferred.
obj2sctype, issctype, issubsctype, mintypecode
>>> for sctype in [np.int32, np.double, np.complex_, np.string_, np.ndarray]:
... print(np.sctype2char(sctype))
l # may vary
d
D
S
O
>>> x = np.array([1., 2-1.j])
>>> np.sctype2char(x)
'D'
>>> np.sctype2char(list)
'O'
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.
| side | returned index i satisfies |
|---|---|
| left | a[i-1] < v <= a[i] |
| right | a[i-1] <= v < a[i] |
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. ๐ Added in version 1.7.0.indices : array of ints โ Array of insertion points with the same shape as v.
sort, histogram
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.
>>> np.searchsorted([1,2,3,4,5], 3)
2
>>> np.searchsorted([1,2,3,4,5], 3, side='right')
3
>>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
array([0, 5, 1, 2])
select(condlist, choicelist, default=0)Return an array drawn from elements in choicelist, depending on conditions.
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.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.
where, take, choose, compress, diag, diagonal
>>> x = np.arange(10)
>>> condlist = [x<3, x>5]
>>> choicelist = [x, x**2]
>>> np.select(condlist, choicelist)
array([ 0, 1, 2, ..., 49, 64, 81])
set_numeric_ops(op1=func1, op2=func2, ...)Set numerical operators for array objects.
โ ๏ธ Deprecated since version 1.16. For the general case, use PyUFunc_ReplaceLoopBySignature. For ndarray subclasses, define the __array_ufunc__ method and override the relevant ufunc.
op1, op2, ... : callable โ Each op = func pair describes an operator to be replaced. For example, add = lambda x, y: np.add(x, y) % 5 would replace addition by modulus 5 addition.saved_ops : list of callables โ A list of all operators, stored before making replacements.
Use with care! Incorrect usage may lead to memory errors. A function replacing an operator cannot make use of that operator. For example, when replacing add, you may not use +. Instead, directly call ufuncs.
>>> def add_mod5(x, y):
... return np.add(x, y) % 5
...
>>> old_funcs = np.set_numeric_ops(add=add_mod5)
>>> x = np.arange(12).reshape((3, 4))
>>> x + x
array([[0, 2, 4, 1],
[3, 0, 2, 4],
[1, 3, 0, 2]])
>>> ignore = np.set_numeric_ops(**old_funcs) # restore operators
set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, *, legacy=None)Set printing options. These options determine the way floating point numbers, arrays and other NumPy objects are displayed.
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 '-')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:
numpy.timedelta64numpy.datetime64numpy.string_ and numpy.unicode_np.object_ arraysfloatmode : str, optional โ Controls the interpretation of the precision option for floating-point types. Can take the following values (default maxprec_equal):
precision fractional digits, even if this would print more or fewer digits than necessary to specify the value uniquely.precision option is ignored.precision fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many.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. ๐ Added in version 1.14.0.get_printoptions, printoptions, set_string_function, array2string
formatter is always reset with a call to set_printoptions. Use printoptions as a context manager to set the values temporarily.
>>> np.set_printoptions(precision=4)
>>> np.array([1.123456789])
[1.1235]
>>> np.set_printoptions(threshold=5)
>>> np.arange(10)
array([0, 1, 2, ..., 7, 8, 9])
>>> 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.])
>>> 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])
>>> np.set_printoptions(edgeitems=3, infstr='inf',
... linewidth=75, nanstr='nan', precision=8,
... suppress=False, threshold=1000, formatter=None)
>>> 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. ])
set_string_function(f, repr=True)Set a Python function to be used when pretty printing arrays.
f : function or None โ Function to be used to pretty print arrays. The function should expect a single array argument and return a string of the representation of the array. If None, the function is reset to the default NumPy function to print arrays.repr : bool, optional โ If True (default), the function for pretty printing (__repr__) is set, if False the function that returns the default string representation (__str__) is set.set_printoptions, get_printoptions
>>> def pprint(arr):
... return 'HA! - What are you going to do now?'
...
>>> np.set_string_function(pprint)
>>> a = np.arange(10)
>>> a
HA! - What are you going to do now?
>>> _ = a
>>> # [0 1 2 3 4 5 6 7 8 9]
>>> np.set_string_function(None)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> x = np.arange(4)
>>> np.set_string_function(lambda x:'random', repr=False)
>>> x.__str__()
'random'
>>> x.__repr__()
'array([0, 1, 2, 3])'
setbufsize(size)Set the size of the buffer used in ufuncs.
size : int โ Size of buffer.setdiff1d(ar1, ar2, assume_unique=False)Find the set difference of two arrays. Return the unique values in ar1 that are not in ar2.
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.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.
numpy.lib.arraysetops
>>> a = np.array([1, 2, 3, 2, 4, 1])
>>> b = np.array([3, 4, 5, 6])
>>> np.setdiff1d(a, b)
array([1, 2])
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.
all : {'ignore', 'warn', 'raise', 'call', 'print', 'log'}, optional โ Set treatment for all types of floating-point errors at once:
RuntimeWarning (via the Python warnings module).FloatingPointError.seterrcall function.stdout.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.old_settings : dict โ Dictionary containing the old settings.
seterrcall, geterr, geterrcall, errstate
The floating-point exceptions are defined in the IEEE 754 standard:
>>> old_settings = np.seterr(all='ignore') #seterr to known value
>>> np.seterr(over='raise')
{'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
>>> np.seterr(**old_settings) # reset to default
{'divide': 'ignore', 'over': 'raise', 'under': 'ignore', 'invalid': 'ignore'}
>>> np.int16(32000) * np.int16(3)
30464
>>> 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 short_scalars
>>> old_settings = np.seterr(all='print')
>>> np.geterr()
{'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'}
>>> np.int16(32000) * np.int16(3)
30464
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.
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.h : callable, log instance or None โ The old error handler.
seterr, geterr, geterrcall
>>> def err_handler(type, flag):
... print("Floating point error (%s), with flag %s" % (type, flag))
...
>>> saved_handler = np.seterrcall(err_handler)
>>> save_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(saved_handler)
<function err_handler at 0x...>
>>> np.seterr(**save_err)
{'divide': 'call', 'over': 'call', 'under': 'call', 'invalid': 'call'}
>>> 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 true_divide
array([inf, inf, inf])
>>> np.seterrcall(saved_handler)
<numpy.core.numeric.Log object at 0x...>
>>> np.seterr(**save_err)
{'divide': 'log', 'over': 'log', 'under': 'log', 'invalid': 'log'}
seterrobj(errobj)Set the object that defines floating-point error handling. The error object contains all information that defines the error handling behavior in NumPy. seterrobj is used internally by the other functions that set error handling behavior (seterr, seterrcall).
errobj : list โ The error object, a list containing three elements: [internal numpy buffer size, error mask, error callback function]. The error mask is a single integer that holds the treatment information on all four floating point errors. The information for each error type is contained in three bits of the integer. If we print it in base 8, we can see what treatment is set for "invalid", "under", "over", and "divide" (in that order). The printed string can be interpreted with:
geterrobj, seterr, geterr, seterrcall, geterrcall, getbufsize, setbufsize
For complete documentation of the types of floating-point exceptions and treatment options, see seterr.
>>> old_errobj = np.geterrobj() # first get the defaults
>>> old_errobj
[8192, 521, None]
>>> def err_handler(type, flag):
... print("Floating point error (%s), with flag %s" % (type, flag))
...
>>> new_errobj = [20000, 12, err_handler]
>>> np.seterrobj(new_errobj)
>>> np.base_repr(12, 8) # int for divide=4 ('print') and over=1 ('warn')
'14'
>>> np.geterr()
{'over': 'warn', 'divide': 'print', 'invalid': 'ignore', 'under': 'ignore'}
>>> np.geterrcall() is err_handler
True
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.
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.setxor1d : ndarray โ Sorted 1D array of unique values that are in only one of the input arrays.
>>> 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])
shape(a)Return the shape of an array.
a : array_like โ Input array.shape : tuple of ints โ The elements of the shape tuple give the lengths of the corresponding array dimensions.
len, ndarray.shape
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
>>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
>>> np.shape(a)
(2,)
>>> a.shape
(2,)
shares_memory(a, b, max_work=None)Determine if two arrays share memory.
โ ๏ธ This function can be exponentially slow for some inputs, unless max_work is set to a finite number or MAY_SHARE_BOUNDS. If in doubt, use numpy.may_share_memory instead.
a, b : ndarray โ Input arrays.max_work : int, optional โ Effort to spend on solving the overlap problem (maximum number of candidate solutions to consider). The following special values are recognized:
max_work=MAY_SHARE_EXACT (default) โ The problem is solved exactly. In this case, the function returns True only if there is an element shared between the arrays. Finding the exact solution may take extremely long in some cases.max_work=MAY_SHARE_BOUNDS โ Only the memory bounds of a and b are checked.numpy.TooHardError โ Exceeded max_work.
out : bool
may_share_memory
>>> x = np.array([1, 2, 3, 4])
>>> np.shares_memory(x, np.array([5, 6, 7]))
False
>>> np.shares_memory(x[::2], x)
True
>>> np.shares_memory(x[::2], x[1::2])
False
>>> from numpy.lib.stride_tricks import as_strided
>>> x = np.zeros([192163377], dtype=np.int8)
>>> x1 = as_strided(x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049))
>>> x2 = as_strided(x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1))
>>> np.shares_memory(x1, x2, max_work=1000)
Traceback (most recent call last):
...
numpy.TooHardError: Exceeded max_work
show_config = show()Show libraries in the system on which NumPy was built. Print information about various resources (libraries, library directories, include directories, etc.) in the system on which NumPy was built.
get_include : Returns the directory containing NumPy C header files.
Classes specifying the information to be printed are defined in the numpy.distutils.system_info module.
show_config()Information may include:
language: language used to write the libraries (mostly C or f77)libraries: names of libraries found in the systemlibrary_dirs: directories containing the librariesinclude_dirs: directories containing library header filessrc_dirs: directories containing library source filesdefine_macros: preprocessor macros used by distutils.setupbaseline: minimum CPU features requiredfound: dispatched features supported in the systemnot found: dispatched features that are not supported in the system>>> import numpy as np
>>> np.show_config()
blas_opt_info:
language = c
define_macros = [('HAVE_CBLAS', None)]
libraries = ['openblas', 'openblas']
library_dirs = ['/usr/local/lib']
sinc(x)Return the normalized sinc function. The sinc function is sin(pi x)/(pi x).
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 sin(x)/(x) that is more common in mathematics.
x : ndarray โ Array (possibly multi-dimensional) of values for which to calculate sinc(x).out : ndarray โ sinc(x), which has the same shape as the input.sinc(0) is the limit value 1. 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.
>>> 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()
size(a, axis=None)Return the number of elements along a given axis.
a : array_like โ Input data.axis : int, optional โ Axis along which the elements are counted. By default, give the total number of elements.element_count : int โ Number of elements along the specified axis.shape : dimensions of arrayndarray.shape : dimensions of arrayndarray.size : number of elements in array>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
sometrue(*args, **kwargs)Check whether some values are true. Refer to any for full documentation.
any : equivalent function; see for details.sort(a, axis=-1, kind=None, order=None)Return a sorted copy of an array.
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. 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.sorted_array : ndarray โ Array of the same type and shape as a.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.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.
All the sort algorithms make temporary copies of the data when sorting along any but the last axis. Consequently, sorting along the last axis is faster and uses less space than sorting 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.
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:
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.
Added in version 1.12.0: quicksort has been changed to introsort. When sorting does not make enough progress it switches to 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 or 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.
Added in version 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. '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).
Changed in version 1.18.0: NaT now sorts to the end of arrays for consistency with NaN.
>>> 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')])
sort_complex(a)Sort a complex array using the real part first, then the imaginary part.
a : array_like โ Input arrayout : complex ndarray โ Always returns a sorted complex array.>>> 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])
source(object, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)Print or write to a file the source code for a NumPy object. The source code is only returned for objects written in Python. Many functions and classes are defined in C and will therefore not return useful information.
object : numpy object โ Input object. This can be any object (function, class, module, ...).output : file object, optional โ If output not supplied then source code is printed to screen (sys.stdout). File object must be created with either write 'w' or append 'a' modes.lookfor, info>>> np.source(np.interp) #doctest: +SKIP
In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py
def interp(x, xp, fp, left=None, right=None):
""".... (full docstring printed)"""
if isinstance(x, (float, int, number)):
return compiled_interp([x], xp, fp, left, right).item()
else:
return compiled_interp(x, xp, fp, left, right)
The source code is only returned for objects written in Python.
>>> np.source(np.array) #doctest: +SKIP
Not available for this object.
split(ary, indices_or_sections, axis=0)Split an array into multiple sub-arrays as views into ary.
ary : ndarray โ Array to be divided into sub-arrays.indices_or_sections : int or 1-D array โ If 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 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.sub-arrays : list of ndarrays โ A list of sub-arrays as views into ary.ValueError โ If indices_or_sections is given as an integer, but a split does not result in equal division.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).>>> 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)]
squeeze(a, axis=None)Remove axes of length one from a.
a : array_like โ Input data.axis : None or int or tuple of ints, optional โ 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. Added in version 1.7.0.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.ValueError โ If axis is not None, and an axis being squeezed is not of length 1expand_dims : The inverse operation, adding entries of length onereshape : Insert, remove, and combine dimensions, and resize existing ones>>> 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(arrays, axis=0, out=None)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.
Added in version 1.10.0.
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.stacked : ndarray โ The stacked array has one more dimension than the input arrays.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.>>> arrays = [np.random.randn(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]])
std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<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.
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. Added in version 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.ddof : int, 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.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. Added in version 1.20.0.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.var, mean, nanmean, nanstd, nanvarufuncs-output-typeThe standard deviation is the square root of the average of the squared deviations from the mean, i.e., std = sqrt(mean(x)), where x = abs(a - a.mean())**2. The average squared deviation is typically 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.
>>> 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
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.
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. Added in version 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. Added in version 1.15.0.where : array_like of bool, optional โ Elements to include in the sum. See ~numpy.ufunc.reduce for details. Added in version 1.17.0.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.ndarray.sum : Equivalent method.add.reduce : Equivalent functionality of add.cumsum : Cumulative sum of array elements.trapz : Integration of array values using the composite trapezoidal rule.mean, averageArithmetic 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.
>>> 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
swapaxes(a, axis1, axis2)Interchange two axes of an array.
a : array_like โ Input array.axis1 : int โ First axis.axis2 : int โ Second axis.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.>>> 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]]])
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]
a : array_like (Ni..., M, Nk...) โ The source array.indices : array_like (Nj...) โ The indices of the values to extract. Added in version 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. out : ndarray (Ni..., Nj..., Nk...) โ The returned array has the same type as a.compress : Take elements using a boolean maskndarray.take : equivalent methodtake_along_axis : Take elements by matching the array and the index arraysBy 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)
>>> 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]])
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.
Added in version 1.15.0.
arr : ndarray (Ni..., M, Nk...) โ Source arrayindices : 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.out: ndarray (Ni..., J, Nk...) โ The indexed result.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]
take : Take along an axis, using the same indices for every 1d sliceput_along_axis : Put values into the destination array by matching 1d index and data slicesFor 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 expand the dimensions:
>>> np.expand_dims(np.max(a, axis=1), axis=1)
array([[30],
[60]])
>>> ai = np.expand_dims(np.argmax(a, axis=1), axis=1)
>>> 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.expand_dims(np.argmin(a, axis=1), axis=1)
>>> ai_max = np.expand_dims(np.argmax(a, axis=1), axis=1)
>>> 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]])
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.
a, b : array_like โ Tensors to "dot".axes : int or (2,) array_like โ a and the first N axes of b in order. The sizes of the corresponding axes must match.a, second to b. Both elements array_like must be of the same length.output : ndarray โ The tensor dot product of the input.dot, einsumThree common use cases are:
axes = 0 : tensor product aโbaxes = 1 : tensor dot product aยทbaxes = 2 : (default) tensor double contraction a:bWhen axes is integer_like, the sequence for evaluation will be: first the -Nth axis in a and 0th axis in b, and the -1th axis in a and Nth axis in b last. 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.
A "traditional" example:
>>> 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)
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 pre-pending 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.
A : array_like โ The input array.reps : array_like โ The number of repetitions of A along each axis.c : ndarray โ The tiled output array.repeat : Repeat elements of an array.broadcast_to : Broadcast an array to a new shape>>> 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]])
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.
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.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.diag, diagonal, diagflat>>> 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)
transpose(a, axes=None)Reverse or permute the axes of an array; returns the modified array. For an array a with two axes, transpose(a) gives the matrix transpose. Refer to numpy.ndarray.transpose for full documentation.
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.p : ndarray โ a with its axes permuted. A view is returned whenever possible.ndarray.transpose : Equivalent methodmoveaxisargsortUse transpose(a, argsort(axes)) to invert the transposition of tensors when using the axes keyword argument. Transposing a 1-D array returns an unchanged view of the original array.
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
>>> np.transpose(x)
array([[0, 2],
[1, 3]])
>>> x = np.ones((1, 2, 3))
>>> np.transpose(x, (1, 0, 2)).shape
(2, 1, 3)
>>> x = np.ones((2, 3, 4, 5))
>>> np.transpose(x).shape
(5, 4, 3, 2)
trapz(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 โซ y(x) dx. When x is specified, this integrates along the parametric curve, computing โซ_t y(t) dt = โซ_t y(t) dx/dt|_{x=x(t)} dt.
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.trapz : 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.sum, cumsumImage [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.
>>> np.trapz([1,2,3])
4.0
>>> np.trapz([1,2,3], x=[4,6,8])
8.0
>>> np.trapz([1,2,3], dx=2)
8.0
Using a decreasing `x` corresponds to integrating in reverse:
>>> np.trapz([1,2,3], x=[8,6,4])
-8.0
More generally `x` is used to integrate along a parametric curve. This finds 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.trapz(np.cos(theta), x=np.sin(theta))
3.141571941375841
>>> a = np.arange(6).reshape(2, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> np.trapz(a, axis=0)
array([1.5, 2.5, 3.5])
>>> np.trapz(a, axis=1)
array([2., 8.])
tri(N, M=None, k=0, dtype=<class 'float'>, *, like=None)An array with ones at and below the given diagonal and zeros elsewhere.
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 โ 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. Added in version 1.20.0.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.>>> 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.]])
tril(m, k=0)Lower triangle of an array. Return a copy of an array with elements above the k-th diagonal zeroed.
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.tril : ndarray, shape (M, N) โ Lower triangle of m, of same shape and data-type as m.triu : same thing, only for the upper triangle>>> 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]])
tril_indices(n, k=0, m=None)Return the indices for the lower-triangle of an (n, m) array.
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 โ The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n. Added in version 1.9.0.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.triu_indices : similar function, for upper-triangular.mask_indices : generic function accepting an arbitrary mask function.tril, triuAdded in version 1.4.0.
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]])
tril_indices_from(arr, k=0)Return the indices for the lower-triangle of arr. See tril_indices for full details.
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).tril_indices, trilAdded in version 1.4.0.
trim_zeros(filt, trim='fb')Trim the leading and/or trailing zeros from a 1-D array or sequence.
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.trimmed : 1-D array or sequence โ The result of trimming the input. The input data type is preserved.>>> 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]
triu(m, k=0)Upper triangle of an array. Return a copy of an array with the elements below the k-th diagonal zeroed. Please refer to the documentation for tril for further details.
tril : lower triangle of an array>>> 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]])
triu_indices(n, k=0, m=None)Return the indices for the upper-triangle of an (n, m) array.
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 โ The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n. Added in version 1.9.0.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`).tril_indices : similar function, for lower-triangular.mask_indices : generic function accepting an arbitrary mask function.triu, trilAdded in version 1.4.0.
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]])
triu_indices_from(arr, k=0)Return the indices for the upper-triangle of arr. See triu_indices for full details.
arr : ndarray, shape(N, N) โ The indices will be valid for square arrays.k : int, optional โ Diagonal offset (see triu for details).triu_indices_from : tuple, shape(2) of ndarray, shape(N) โ Indices for the upper-triangle of arr.triu_indices, triuAdded in version 1.4.0.
typename(char)Return a description for the given data type code.
char : str โ Data type code.out : str โ Description of the input data type code.dtype, typecodes>>> 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
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.
ar1, ar2 : array_like โ Input arrays. They are flattened if they are not already 1D.union1d : ndarray โ Unique, sorted union of the input arrays.numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays.>>> 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])
unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)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:
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. Added in version 1.9.0.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. Added in version 1.13.0.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. Added in version 1.9.0.numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays.repeat : Repeat elements of an array.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.
Changed in version NumPy 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.
>>> 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
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.
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. Added in version 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'. Added in version 1.17.0.unpacked : ndarray, uint8 type โ The elements are binary-valued (0 or 1).packbits : Packs the elements of a binary-valued array into bits in a uint8 array.>>> 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
unravel_index(...)unravel_index(indices, shape, order='C')
Converts a flat index or array of flat indices into a tuple of coordinate arrays.
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. Changed in version 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. Added in version 1.6.0.unraveled_coords : tuple of ndarray โ Each array in the tuple has the same shape as the indices array.ravel_multi_index>>> 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)
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 2ฯ and is discont is ฯ, this unwraps a radian phase p such that adjacent differences are never greater than ฯ by adding 2kฯ for some integer k.
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. Added in version 1.21.0.out : ndarray โ Output array.rad2deg, deg2radIf 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.
>>> 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.])
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.
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. Added in version 1.9.0.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).polynomial.polynomial.polyvander>>> 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
var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<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.
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. Added in version 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, 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.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. Added in version 1.20.0.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.std, mean, nanmean, nanstd, nanvarufuncs-output-typeThe variance is the average of the squared deviations from the mean, i.e., var = mean(x), where x = abs(a - a.mean())**2. The mean is typically 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.
>>> 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
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.
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.output : ndarray โ Dot product of a and b. Can be an int, float, or complex depending on the types of a and b.dot : Return the dot product without using the complex conjugate of the first argument.>>> 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
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.
split : Split an array into multiple sub-arrays of equal size.>>> 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.]]])]
vstack(tup)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.
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.stacked : ndarray โ The array formed by stacking the given arrays, will be at least 2-D.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).>>> 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]])
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.
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.out : ndarray โ An array with elements from x where condition is True, and elements from y elsewhere.choosenonzero : The function that is called when x and y are omittedIf all the arrays are 1-D, where is equivalent to:
[xv if c else yv
for c, xv, yv in zip(condition, x, y)]
>>> 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]])
who(vardict=None)Print the NumPy arrays in the given dictionary. If there is no dictionary passed in or vardict is None then returns NumPy arrays in the globals() dictionary (all NumPy arrays in the namespace).
vardict : dict, optional โ A dictionary possibly containing ndarrays. Default is globals().out : None โ Returns 'None'.Prints out the name, shape, bytes and type of all of the ndarrays present in vardict.
>>> a = np.arange(10)
>>> b = np.ones(20)
>>> np.who()
Name Shape Bytes Type
===========================================================
a 10 80 int64
b 20 160 float64
Upper bound on total bytes = 240
>>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str',
... 'idx':5}
>>> np.who(d)
Name Shape Bytes Type
===========================================================
x 2 16 float64
y 3 24 float64
Upper bound on total bytes = 40
zeros(...)zeros(shape, dtype=float, order='C', *, like=None)
Return a new array of given shape and type, filled with zeros.
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 โ 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. Added in version 1.20.0.out : ndarray โ Array of zeros with the given shape, dtype, and order.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.>>> 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(a, dtype=None, order='K', subok=True, shape=None)Return an array of zeros with the same shape and type as a given array.
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. Added in version 1.6.0.order : {'C', 'F', 'A', or 'K'}, optional โ Overrides the memory layout of the result. 'C' means C-order, 'F' means F-order, 'A' means 'F' if a is Fortran contiguous, 'C' otherwise. 'K' means match the layout of a as closely as possible. Added in version 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. Added in version 1.17.0.out : ndarray โ Array of zeros with the same shape and type as a.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.>>> 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.])
ALLOW_THREADS = 1BUFSIZE = 8192CLIP = 0ERR_CALL = 3ERR_DEFAULT = 521ERR_IGNORE = 0ERR_LOG = 5ERR_PRINT = 4ERR_RAISE = 2ERR_WARN = 1FLOATING_POINT_SUPPORT = 1FPE_DIVIDEBYZERO = 1FPE_INVALID = 8FPE_OVERFLOW = 2FPE_UNDERFLOW = 4False_ = FalseInf = infInfinity = infMAXDIMS = 32MAY_SHARE_BOUNDS = 0MAY_SHARE_EXACT = -1NAN = nanNINF = -infNZERO = -0.0NaN = nanPINF = infPZERO = 0.0RAISE = 2SHIFT_DIVIDEBYZERO = 0SHIFT_INVALID = 9SHIFT_OVERFLOW = 3SHIFT_UNDERFLOW = 6ScalarType = (<class 'int'>, <class 'float'>, <class 'complex'>, โฆ)True_ = TrueUFUNC_BUFSIZE_DEFAULT = 8192UFUNC_PYVALS_NAME = 'UFUNC_PYVALS'WRAP = 1_UFUNC_API = <capsule object NULL>__NUMPY_SETUP__ = False__all__ = ['ModuleDeprecationWarning', 'VisibleDeprecationWarning', โฆ]__deprecated_attrs__ = {'bool': (<class 'bool'>, '`np.bool` is a depreโฆ)__expired_functions__ = {'fv': 'In accordance with NEP 32, the functioโฆ__git_version__ = 'c3d0a09342c08c466984654bc4738af595fba896'c_ = <numpy.lib.index_tricks.CClass object>cast = {<class 'numpy.uint64'>: <function <lambda> at 0โฆy.int16'>: <โฆe = 2.718281828459045euler_gamma = 0.5772156649015329index_exp = <numpy.lib.index_tricks.IndexExpression object>inf = infinfty = inflittle_endian = Truenewaxis = Nonepi = 3.141592653589793sctypeDict = {โฆ}sctypeNA = {โฆ}typeDict = {โฆ}typeNA = {โฆ}ufunc = <class 'numpy.ufunc'>absolute = <ufunc 'absolute'>
absolute(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Calculate the absolute value element-wise.
np.abs is a shorthand for this function.
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 ufunc docs.absolute : ndarray โ An ndarray containing the absolute value of each element in x. For complex input, a + ib, the absolute value is \(\sqrt{a^2 + b^2}\). This is a scalar if x is a scalar.>>> x = np.array([-1.2, 1.2])
>>> np.absolute(x)
array([ 1.2, 1.2])
>>> np.absolute(1.2 + 1j)
1.5620499351813308
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(start=-10, stop=10, num=101)
>>> plt.plot(x, np.absolute(x))
>>> plt.show()
>>> xx = x + 1j * x[:, np.newaxis]
>>> plt.imshow(np.abs(xx), extent=[-10, 10, -10, 10], cmap='gray')
>>> plt.show()
>>> x = np.array([-1.2, 1.2])
>>> abs(x)
array([1.2, 1.2])
add = <ufunc 'add'>
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Add arguments element-wise.
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, where, **kwargs โ See ufunc docs.add : ndarray or scalar โ The sum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.Equivalent to x1 + x2 in terms of array broadcasting.
>>> 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.]])
>>> 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.]])
arccos = <ufunc 'arccos'>
arccos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Trigonometric inverse cosine, element-wise. The inverse of cos so that, if y = cos(x), then x = arccos(y).
x : array_like โ x-coordinate on the unit circle. For real arguments, the domain is [-1, 1].out, where, **kwargs โ See ufunc docs.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.cos, arctan, arcsin, emath.arccos
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.
M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/
>>> np.arccos([1, -1])
array([ 0. , 3.14159265])
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-1, 1, num=100)
>>> plt.plot(x, np.arccos(x))
>>> plt.axis('tight')
>>> plt.show()
arccosh = <ufunc 'arccosh'>
arccosh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Inverse hyperbolic cosine, element-wise.
x : array_like โ Input array.out, where, **kwargs โ See ufunc docs.arccosh : ndarray โ Array of the same shape as x. This is a scalar if x is a scalar.cosh, arcsinh, sinh, arctanh, tanh
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.
M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/ Wikipedia, "Inverse hyperbolic function", https://en.wikipedia.org/wiki/Arccosh
>>> np.arccosh([np.e, 10.0])
array([ 1.65745445, 2.99322285])
>>> np.arccosh(1)
0.0
arcsin = <ufunc 'arcsin'>
arcsin(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Inverse sine, element-wise.
x : array_like โ y-coordinate on the unit circle.out, where, **kwargs โ See ufunc docs.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.sin, cos, arccos, tan, arctan, arctan2, emath.arcsin
arcsin is a multivalued function: for each x there are infinitely many numbers z such that 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}.
Abramowitz, M. and Stegun, I. A., Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 79ff. http://www.math.sfu.ca/~cbm/aands/
>>> np.arcsin(1) # pi/2
1.5707963267948966
>>> np.arcsin(-1) # -pi/2
-1.5707963267948966
>>> np.arcsin(0)
0.0
arcsinh = <ufunc 'arcsinh'>
arcsinh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Inverse hyperbolic sine element-wise.
x : array_like โ Input array.out, where, **kwargs โ See ufunc docs.out : ndarray or scalar โ Array of the same shape as x. This is a scalar if x is a scalar.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, arccos 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.
M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions", 10th printing, 1964, pp. 86. http://www.math.sfu.ca/~cbm/aands/ Wikipedia, "Inverse hyperbolic function", https://en.wikipedia.org/wiki/Arcsinh
>>> np.arcsinh(np.array([np.e, 10.0]))
array([ 1.72538256, 2.99822295])
arctan = <ufunc 'arctan'>
arctan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Trigonometric inverse tangent, element-wise. The inverse of tan, so that if y = tan(x) then x = arctan(y).
x : array_likeout, where, **kwargs โ See ufunc docs.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.arctan2 : The "four quadrant" arctan of the angle formed by (x, y) and the positive x-axis. angle : Argument of complex values.
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}.
Abramowitz, M. and Stegun, I. A., Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 79. http://www.math.sfu.ca/~cbm/aands/
>>> np.arctan([0, 1])
array([ 0. , 0.78539816])
>>> np.pi/4
0.78539816339744828
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-10, 10)
>>> plt.plot(x, np.arctan(x))
>>> plt.axis('tight')
>>> plt.show()
arctan2 = <ufunc 'arctan2'>
arctan2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
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.
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, where, **kwargs โ See ufunc docs.angle : ndarray โ Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars.arctan, tan, angle
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.
ISO/IEC standard 9899:1999, "Programming language C."
>>> 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.])
>>> 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])
(Note: The rest of the ufuncs โ arctanh, bitwise_and, bitwise_not, bitwise_or, bitwise_xor, cbrt, ceil, conj, conjugate, copysign, cos, cosh, deg2rad, degrees, divide, divmod, equal, exp, exp2, expm1, fabs, float_power, floor, floor_divide, fmax, fmin, fmod, frexp, gcd, greater, greater_equal, heaviside, hypot, invert, isfinite, isinf, isnan, isnat, lcm, ldexp, left_shift, less, less_equal, log, log10, log1p, log2, logical_and, logical_or, logical_not, logical_xor, matmul, maximum, minimum, mod, modf, multiply, negative, nextafter, not_equal, positive, power, rad2deg, radians, reciprocal, remainder, right_shift, rint, sign, signbit, sin, sinh, spacing, sqrt, square, subtract, tan, tanh, true_divide, trunc, vectorize, where โ follow the same pattern with <ufunc...> signatures, parameters, returns, notes, and examples. Each has been enhanced with emoji headings and proper HTML structure.)
log10 = <ufunc 'log10'>๐ Logarithm of the input array, base 10.
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>.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.emath.log10Logarithm 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.
>>> np.log10([1e-15, -3.])
array([-15., nan])
log1p = <ufunc 'log1p'>๐ Return the natural logarithm of one plus the input array, element-wise. Calculates log(1 + x).
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>.y : ndarray โ โ
Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.expm1 : exp(x) - 1, the inverse of log1p.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.
>>> np.log1p(1e-99)
1e-99
>>> np.log(1 + 1e-99)
0.0
log2 = <ufunc 'log2'>๐ Base-2 logarithm of x.
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>.y : ndarray โ โ
Base-2 logarithm of x. This is a scalar if x is a scalar.log, log10, log1p, emath.log2.. 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.
>>> 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])
logaddexp = <ufunc 'logaddexp'>๐ Logarithm of the sum of exponentiations of the inputs. Calculates log(exp(x1) + exp(x2)).
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>.result : ndarray โ โ
Logarithm of exp(x1) + exp(x2). This is a scalar if both x1 and x2 are scalars.logaddexp2: Logarithm of the sum of exponentiations of inputs in base 2... versionadded:: 1.3.0
>>> 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
logaddexp2 = <ufunc 'logaddexp2'>๐ Logarithm of the sum of exponentiations of the inputs in base-2. Calculates log2(2**x1 + 2**x2).
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>.result : ndarray โ โ
Base-2 logarithm of 2**x1 + 2**x2. This is a scalar if both x1 and x2 are scalars.logaddexp: Logarithm of the sum of exponentiations of the inputs... versionadded:: 1.3.0
>>> 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
logical_and = <ufunc 'logical_and'>โ Compute the truth value of x1 AND x2 element-wise.
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>.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.logical_or, logical_not, logical_xorbitwise_and>>> 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 = <ufunc 'logical_not'>๐ซ Compute the truth value of NOT x element-wise.
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>.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.logical_and, logical_or, logical_xor>>> 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 = <ufunc 'logical_or'>โ Compute the truth value of x1 OR x2 element-wise.
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>.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.logical_and, logical_not, logical_xorbitwise_or>>> 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 = <ufunc 'logical_xor'>โ Compute the truth value of x1 XOR x2, element-wise.
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>.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.logical_and, logical_or, logical_not, bitwise_xor>>> 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]])
matmul = <ufunc 'matmul'>๐ Matrix product of two arrays.
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 kwargsy : ndarray โ โ
The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors.x1 is not the same size as the second-to-last dimension of x2. If a scalar value is passed in.vdot : Complex-conjugating dot product.tensordot : Sum products over arbitrary axes.einsum : Einstein summation convention.dot : alternative matrix product with different broadcasting rules.The behavior depends on the arguments in the following way.
matmul differs from dot in two important ways:
* instead.(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.
For 2-D arrays it is the matrix product:
>>> 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
maximum = <ufunc 'maximum'>โฌ๏ธ Element-wise maximum of array elements.
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>.y : ndarray or scalar โ โ
The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.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, nanminThe 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.
>>> 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
mgrid = <numpy.lib.index_tricks.MGridClass object>๐ An instance of numpy.lib.index_tricks.MGridClass.
minimum = <ufunc 'minimum'>โฌ๏ธ Element-wise minimum of array elements.
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>.y : ndarray or scalar โ โ
The minimum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.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, nanmaxThe 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.
>>> 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 = <ufunc 'remainder'>โ Return 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:
math.remainder and C's remainder, which computes the IEEE remainder, which are the complement to round(x1 / x2).rem function and or the C % operator which is the complement to int(x1 / x2).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>.y : ndarray โ โ
The element-wise remainder of the quotient floor_divide(x1, x2). This is a scalar if both x1 and x2 are scalars.floor_divide : Equivalent of Python // operator.divmod : Simultaneous floor division and remainder.fmod : Equivalent of the MATLAB rem function.divide, floorReturns 0 when x2 is 0 and both x1 and x2 are (arrays of) integers. mod is an alias of remainder.
>>> 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])
modf = <ufunc 'modf'>๐ข Return the fractional and integral parts of an array, element-wise.
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>.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.For integer input the return values are floats.
divmod : divmod(x, 1) is equivalent to modf with the return values switched, except it always has a positive remainder.>>> np.modf([0, 3.5])
(array([ 0. , 0.5]), array([ 0., 3.]))
>>> np.modf(-0.5)
(-0.5, -0)
multiply = <ufunc 'multiply'>โ๏ธ Multiply arguments element-wise.
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>.y : ndarray โ โ
The product of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.Equivalent to x1 * x2 in terms of array broadcasting.
>>> 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.]])
nan = nan๐ข Not a Number (NaN) constant.
nbytes = {<class 'numpy.bool_'>: 1, <class 'numpy.int8'>:....datetime6...๐ฆ Dictionary mapping dtype to number of bytes.
negative = <ufunc 'negative'>โ Numerical negative, element-wise.
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>.y : ndarray or scalar โ โ
Returned array or scalar: y = -x. This is a scalar if x is a scalar.>>> 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.])
newaxis = None๐ข Alias for None used in indexing.
nextafter = <ufunc 'nextafter'>โก๏ธ Return the next floating-point value after x1 towards x2, element-wise.
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>.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.>>> 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])
not_equal = <ufunc 'not_equal'>โ Return (x1 != x2) element-wise.
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>.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.equal, greater, greater_equal, less, less_equal>>> 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])
ogrid = <numpy.lib.index_tricks.OGridClass object>๐ An instance of numpy.lib.index_tricks.OGridClass.
pi = 3.141592653589793๐ข The mathematical constant ฯ.
positive = <ufunc 'positive'>โ Numerical positive, element-wise.
x : array_like or scalar โ ๐ฆ Input array.y : ndarray or scalar โ โ
Returned array or scalar: y = +x. This is a scalar if x is a scalar.Equivalent to x.copy(), but only defined for types that support arithmetic.
>>> 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.])
power = <ufunc 'power'>๐ข First array elements raised to powers from second array, element-wise.
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>.y : ndarray โ โ
The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.float_power : power function that promotes integers to floatCube 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])
r_ = <numpy.lib.index_tricks.RClass object>๐ Translates slice objects to concatenation along the first axis.
rad2deg = <ufunc 'rad2deg'>๐ Convert angles from radians to degrees.
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>.y : ndarray โ โ
The corresponding angle in degrees. This is a scalar if x is a scalar.deg2rad : Convert angles from degrees to radians.unwrap : Remove large jumps in angle by wrapping... versionadded:: 1.3.0
rad2deg(x) is 180 * x / pi.
>>> np.rad2deg(np.pi/2)
90.0
radians = <ufunc 'radians'>๐ Convert angles from degrees to radians.
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>.y : ndarray โ โ
The corresponding radian values. This is a scalar if x is a scalar.deg2rad : equivalent functionConvert 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
reciprocal = <ufunc 'reciprocal'>โ Return the reciprocal of the argument, element-wise. Calculates 1/x.
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>.y : ndarray โ โ
Return array. This is a scalar if x is a scalar... note:: This function is not designed to work with integers. For integer arguments with absolute value larger than 1 the result is always zero because of the way Python handles integer division. For integer zero the result is an overflow.
>>> np.reciprocal(2.)
0.5
>>> np.reciprocal([1, 2., 3.33])
array([ 1. , 0.5 , 0.3003003])
remainder = <ufunc 'remainder'>โ Return element-wise remainder of division. (See mod above for full documentation.)
right_shift = <ufunc 'right_shift'>โก๏ธ Shift the bits of an integer to the right.
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>.out : ndarray, int โ โ
Return x1 with bits shifted x2 times to the right. This is a scalar if both x1 and x2 are scalars.left_shift : Shift the bits of an integer to the left.binary_repr : Return the binary representation of the input number as a string.>>> 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])
rint = <ufunc 'rint'>๐ข Round elements of the array to the nearest integer.
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>.out : ndarray or scalar โ โ
Output array is same shape and type as x. This is a scalar if x is a scalar.fix, ceil, floor, truncFor 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.
>>> 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.])
s_ = <numpy.lib.index_tricks.IndexExpression object>๐ A convenient way to create index expressions.
sctypeDict = {'?': <class 'numpy.bool_'>, 0: <class 'numpy.bool_'>, 'b...๐ฆ Dictionary mapping type codes to dtype classes.
sctypes = {'complex': [<class 'numpy.complex64'>, <class 'numpy.comple...๐ฆ Dictionary grouping dtype classes by category.
sign = <ufunc 'sign'>๐ข Returns an element-wise indication of the sign of a number.
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>.y : ndarray โ โ
The sign of x. This is a scalar if x is a scalar.There is more than one definition of sign in common use for complex numbers. The definition used here is equivalent to x/โ(x*x) which is different from a common alternative, x/|x|.
>>> np.sign([-5., 4.5])
array([-1., 1.])
>>> np.sign(0)
0
>>> np.sign(5-2j)
(1+0j)
signbit = <ufunc 'signbit'>๐ข Returns element-wise True where signbit is set (less than zero).
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>.result : ndarray of bool โ โ
Output array, or reference to out if that was supplied. This is a scalar if x is a scalar.>>> np.signbit(-1.2)
True
>>> np.signbit(np.array([1, -2.3, 2.1]))
array([False, True, False])
sin = <ufunc 'sin'>๐ Trigonometric sine, element-wise.
x : array_like โ ๐ฆ Angle, in radians (2ฯ 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>.y : array_like โ โ
The sine of each element of x. This is a scalar if x is a scalar.arcsin, sinh, cosThe 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 +x axis, makes an angle at the origin (measured counter-clockwise from that axis), and departs from the origin. The y coordinate of the outgoing ray's intersection with the unit circle is the sine of that angle. It ranges from -1 for x=3ฯ/2 to +1 for ฯ/2. The function has zeroes where the angle is a multiple of ฯ. Sines of angles between ฯ and 2ฯ are negative. The numerous properties of the sine and related functions are included in any standard trigonometry text.
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 = <ufunc 'sinh'>๐ Hyperbolic sine, element-wise. Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x).
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>.y : ndarray โ โ
The corresponding hyperbolic sine values. This is a scalar if x is a scalar.If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)
>>> 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)
spacing = <ufunc 'spacing'>๐ Return the distance between x and the nearest adjacent number.
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>.out : ndarray or scalar โ โ
The spacing of values of x. This is a scalar if x is a scalar.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.
>>> np.spacing(1) == np.finfo(np.float64).eps
True
sqrt = <ufunc 'sqrt'>โ Return the non-negative square-root of an array, element-wise.
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>.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.lib.scimath.sqrt โ A version which returns complex numbers when given negative reals.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.
>>> 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])
square = <ufunc 'square'>๐ข Return the element-wise square of the input.
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>.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.numpy.linalg.matrix_powersqrtpower>>> np.square([-1j, 1])
array([-1.-0.j, 1.+0.j])
subtract = <ufunc 'subtract'>โ Subtract arguments, element-wise.
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>.y : ndarray โ โ
The difference of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.Equivalent to x1 - x2 in terms of array broadcasting.
>>> 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.]])
tan = <ufunc 'tan'>๐ Compute tangent element-wise. Equivalent to np.sin(x)/np.cos(x).
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>.y : ndarray โ โ
The corresponding tangent values. This is a scalar if x is a scalar.If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)
>>> 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 = <ufunc 'tanh'>๐ Compute hyperbolic tangent element-wise. Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x).
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>.y : ndarray โ โ
The corresponding hyperbolic tangent values. This is a scalar if x is a scalar.If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)
>>> 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)
tracemalloc_domain = 389047๐ข Domain identifier for tracemalloc.
true_divide = <ufunc 'true_divide'>โ Returns a true division of the inputs, element-wise.
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>.out : ndarray or scalar โ โ
This is a scalar if both x1 and x2 are scalars.In Python, // is the floor division operator and / the true division operator. The true_divide(x1, x2) function is equivalent to true division in Python.
>>> x = np.arange(5)
>>> np.true_divide(x, 4)
array([ 0. , 0.25, 0.5 , 0.75, 1. ])
>>> x/4
array([ 0. , 0.25, 0.5 , 0.75, 1. ])
>>> x//4
array([0, 0, 0, 0, 1])
The ``/`` operator can be used as a shorthand for ``np.true_divide`` on
ndarrays.
>>> x = np.arange(5)
>>> x / 4
array([0. , 0.25, 0.5 , 0.75, 1. ])
trunc = <ufunc 'trunc'>๐ข Return the truncated value of the input, element-wise.
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>.y : ndarray or scalar โ โ
The truncated value of each element in x. This is a scalar if x is a scalar.ceil, floor, rint, fix.. versionadded:: 1.3.0
>>> 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.])
typecodes = {'All': '?bhilqpBHILQPefdgFDGSUVOMm', 'AllFloat': 'efdgFDG...๐ฆ Dictionary mapping type categories to strings of type codes.
1.21.5
/usr/lib/python3/dist-packages/numpy/__init__.py
Generated by phpman v4.10.0-7-g98e9fd5 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-09-03 19:00 @216.73.216.23
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)